From 0c3214c649a7d6e428e767dfd1044018e699ed05 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:05:52 +0000 Subject: [PATCH 1/7] factory-server: record the cost OpenRouter charged After an OpenRouter run the server reads each generation's total_cost from GET /api/v1/generation with the run's key and adds the sum through Store::add_cost, not marked estimated. The lookup runs in a background task with retries for about a minute, so it never fails the run or delays the job's next step. When an id stays unreadable or the output showed none, the run adds no cost and the log says so with the token counts. A fetched $0 shows $0.00. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/lib.rs | 5 +- crates/factory-server/src/main.rs | 9 +- crates/factory-server/src/openrouter.rs | 141 +++++++++ crates/factory-server/src/scheduler.rs | 93 +++++- crates/factory-server/src/store.rs | 5 +- crates/factory-server/tests/dashboard.rs | 29 +- .../factory-server/tests/openrouter_http.rs | 60 +++- crates/factory-server/tests/openrouter_run.rs | 13 +- crates/factory-server/tests/scheduler.rs | 285 ++++++++++++++++-- .../tests/support/copilot_harness.rs | 12 +- docs/design.md | 15 +- 11 files changed, 598 insertions(+), 69 deletions(-) diff --git a/crates/factory-server/src/lib.rs b/crates/factory-server/src/lib.rs index c474661..f6458dc 100644 --- a/crates/factory-server/src/lib.rs +++ b/crates/factory-server/src/lib.rs @@ -59,8 +59,9 @@ pub use mcp::{ McpError, McpProjectSettings, McpServer, McpStages, McpTool, McpToolState, McpTransport, }; pub use openrouter::{ - HttpOpenRouterApi, OPENROUTER_BASE_URL, OpenRouterApi, OpenRouterKeyFuture, OpenRouterModel, - OpenRouterModelsFuture, parse_models, + GenerationError, HttpOpenRouterApi, OPENROUTER_BASE_URL, OpenRouterApi, OpenRouterCosts, + OpenRouterGenerationFuture, OpenRouterKeyFuture, OpenRouterModel, OpenRouterModelsFuture, + parse_generation_cost, parse_models, }; pub use podman::PodmanExecutor; pub use projects::{ diff --git a/crates/factory-server/src/main.rs b/crates/factory-server/src/main.rs index dd615d1..50a5daa 100644 --- a/crates/factory-server/src/main.rs +++ b/crates/factory-server/src/main.rs @@ -7,10 +7,10 @@ use factory_runner::{ForgeKind, Git, GitHub, GitLab, WorkerConfig}; use factory_server::{ Accounts, AgentRegistry, ClaudeToken, CodexLogin, DeviceLogin, Forges, GhRepos, GlabRepos, HttpForgejoProbe, HttpLocalServerProbe, HttpMcpChecker, HttpOpenRouterApi, LocalSecrets, - LoginSpec, McpChecker, McpRuntime, McpWarnings, OpenRouterApi, PlanUsageCache, PodmanExecutor, - PodmanLogin, Projects, ProxyEvent, ProxyEventFn, RunTokens, Scheduler, SecretStore, Store, - StoreUpstreams, UnavailableSecrets, Upstreams, WorkerSlots, app_with_forgejo_probe, - import_tomls, master_key_from_env, parse_admins, proxy_app_with_roots, + LoginSpec, McpChecker, McpRuntime, McpWarnings, OpenRouterApi, OpenRouterCosts, PlanUsageCache, + PodmanExecutor, PodmanLogin, Projects, ProxyEvent, ProxyEventFn, RunTokens, Scheduler, + SecretStore, Store, StoreUpstreams, UnavailableSecrets, Upstreams, WorkerSlots, + app_with_forgejo_probe, import_tomls, master_key_from_env, parse_admins, proxy_app_with_roots, }; use tokio::sync::Notify; @@ -286,6 +286,7 @@ async fn main() -> Result<(), Box> { warnings: Arc::clone(&mcp_warnings), }, Accounts::new(Arc::clone(&store), Arc::clone(&secrets), forges.clone()), + OpenRouterCosts::new(Arc::clone(&openrouter_api)), ); slots = scheduler.slots(); tokio::spawn(scheduler.run()); diff --git a/crates/factory-server/src/openrouter.rs b/crates/factory-server/src/openrouter.rs index 721af5e..6af017d 100644 --- a/crates/factory-server/src/openrouter.rs +++ b/crates/factory-server/src/openrouter.rs @@ -3,6 +3,7 @@ use std::future::Future; use std::pin::Pin; +use std::sync::Arc; use std::time::Duration; use crate::local_server::ModelsError; @@ -27,6 +28,40 @@ pub type OpenRouterModelsFuture<'a> = pub type OpenRouterKeyFuture<'a> = Pin> + Send + 'a>>; +pub type OpenRouterGenerationFuture<'a> = + Pin> + Send + 'a>>; + +/// Why a generation's cost could not be read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GenerationError { + /// `OpenRouter` does not know the generation yet, or its answer holds no + /// cost yet. It can show up a moment after the run ends. + NotReady, + /// The request failed. + Failed(ModelsError), +} + +impl GenerationError { + /// Whether asking again later can help. A 401 or 403 means `OpenRouter` + /// refuses the key, which waiting does not change. + #[must_use] + pub fn retryable(&self) -> bool { + !matches!( + self, + GenerationError::Failed(ModelsError::Status(401 | 403)) + ) + } +} + +impl std::fmt::Display for GenerationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + GenerationError::NotReady => f.write_str("OpenRouter has no cost for it yet"), + GenerationError::Failed(error) => error.fmt(f), + } + } +} + /// Talks to `OpenRouter`. A trait so tests can answer without a network. pub trait OpenRouterApi: Send + Sync { /// Lists the models that support tool calls, sending `key` as a bearer @@ -48,6 +83,68 @@ pub trait OpenRouterApi: Send + Sync { /// [`ModelsError::Timeout`] when it cannot be reached. The text never holds /// the key. fn check_key<'a>(&'a self, key: &'a str) -> OpenRouterKeyFuture<'a>; + + /// Reads what `OpenRouter` charged for generation `id` in USD, with one + /// `GET /api/v1/generation?id=` using `key`. + /// + /// # Errors + /// + /// Returns [`GenerationError::NotReady`] for a 404 or an answer with no + /// `data.total_cost`, which can hold right after a run, and + /// [`GenerationError::Failed`] for any other failure. The text never holds + /// the key. + fn generation<'a>(&'a self, id: &'a str, key: &'a str) -> OpenRouterGenerationFuture<'a>; +} + +/// Reads what a run was charged from the generations its output showed. +pub struct OpenRouterCosts { + api: Arc, + delays: Vec, +} + +impl OpenRouterCosts { + /// Asks again after 2, 4, 8, 16 and 30 seconds, so a generation that + /// `OpenRouter` has not stored yet is waited for about a minute. + #[must_use] + pub fn new(api: Arc) -> Self { + Self::with_delays(api, [2, 4, 8, 16, 30].map(Duration::from_secs).to_vec()) + } + + /// As [`Self::new`], with the waits between the rounds of asking given. + #[must_use] + pub fn with_delays(api: Arc, delays: Vec) -> Self { + OpenRouterCosts { api, delays } + } + + /// The sum of the costs of the generations `ids`, read with `key`. Each + /// round asks only for the ids still unread. `None` when an id stays + /// unread after the last round, `OpenRouter` refuses the key, or `ids` is + /// empty. + pub async fn total(&self, key: &str, ids: &[String]) -> Option { + if ids.is_empty() { + return None; + } + let mut costs: Vec> = vec![None; ids.len()]; + for round in 0..=self.delays.len() { + for (id, slot) in ids.iter().zip(&mut costs) { + if slot.is_some() { + continue; + } + match self.api.generation(id, key).await { + Ok(cost) => *slot = Some(cost), + Err(error) if !error.retryable() => return None, + Err(_) => {} + } + } + if costs.iter().all(Option::is_some) { + break; + } + if let Some(delay) = self.delays.get(round) { + tokio::time::sleep(*delay).await; + } + } + costs.into_iter().sum() + } } /// The production [`OpenRouterApi`]. It follows no redirect, so the key never @@ -131,6 +228,50 @@ impl OpenRouterApi for HttpOpenRouterApi { } }) } + + fn generation<'a>(&'a self, id: &'a str, key: &'a str) -> OpenRouterGenerationFuture<'a> { + Box::pin(async move { + let client = self + .client + .as_ref() + .ok_or(GenerationError::Failed(ModelsError::Connect))?; + let response = client + .get(format!("{}/v1/generation", self.base_url)) + .query(&[("id", id)]) + .bearer_auth(key) + .send() + .await + .map_err(|err| GenerationError::Failed(transport(&err)))?; + let status = response.status(); + if status == reqwest::StatusCode::NOT_FOUND { + return Err(GenerationError::NotReady); + } + if !status.is_success() { + return Err(GenerationError::Failed(ModelsError::Status( + status.as_u16(), + ))); + } + let body = response + .bytes() + .await + .map_err(|err| GenerationError::Failed(transport(&err)))?; + parse_generation_cost(&body) + }) + } +} + +/// The `data.total_cost` of a generation answer. +/// +/// # Errors +/// +/// Returns [`GenerationError::NotReady`] when the body holds no non-negative +/// cost. +pub fn parse_generation_cost(body: &[u8]) -> Result { + serde_json::from_slice::(body) + .ok() + .and_then(|value| value.get("data")?.get("total_cost")?.as_f64()) + .filter(|cost| cost.is_finite() && *cost >= 0.0) + .ok_or(GenerationError::NotReady) } /// The models of an `OpenRouter` list that support tools, in its order. A model diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index cef3655..889c2a9 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -24,7 +24,7 @@ use crate::accounts::{ }; use crate::cost::{codex_cost, format_cost}; use crate::mcp::{McpServer, McpTransport}; -use crate::openrouter::OPENROUTER_BASE_URL; +use crate::openrouter::{OPENROUTER_BASE_URL, OpenRouterCosts}; use crate::projects::{Project, Projects, StageAgents}; use crate::proxy::RunTokens; use crate::secrets::{SecretError, SecretRef, SecretStore}; @@ -894,6 +894,8 @@ pub struct Scheduler { not_before: Mutex>, slots: Arc, mcp: McpRuntime, + /// Reads what an `OpenRouter` run was charged, after the run. + costs: Arc, /// When each project's Renovate pull requests were last listed. discovered: Mutex>, /// The (job, login) pairs whose ignored comments the job's log already @@ -922,7 +924,21 @@ fn rerun_request( } } +/// The key an `OpenRouter` run pays with, kept before the request moves into +/// the run so the cost lookup afterwards can use it. +fn openrouter_key_of(request: &AgentRequest) -> Option { + request + .provider + .as_ref() + .filter(|provider| provider.target.kind == ProviderKind::OpenRouter) + .and_then(|provider| provider.target.key.clone()) +} + impl Scheduler { + #[allow( + clippy::too_many_arguments, + reason = "the scheduler wires each long-lived dependency it shares with its tasks" + )] pub fn new( store: Arc, projects: Arc, @@ -931,6 +947,7 @@ impl Scheduler { data_dir: PathBuf, mcp: McpRuntime, accounts: Accounts, + costs: OpenRouterCosts, ) -> Arc { Arc::new(Scheduler { store, @@ -942,6 +959,7 @@ impl Scheduler { not_before: Mutex::new(HashMap::new()), slots: Arc::new(WorkerSlots::new()), mcp, + costs: Arc::new(costs), discovered: Mutex::new(HashMap::new()), ignored_noted: Mutex::new(HashSet::new()), }) @@ -2376,8 +2394,8 @@ impl Scheduler { }); // The model the run passed, kept before the request moves into the run, // so a Codex run can look up its price by it afterwards. - let model = request.model.clone(); - let agent = request.agent; + let (model, agent) = (request.model.clone(), request.agent); + let openrouter_key = openrouter_key_of(&request); let report = self .executor .run_agent(settings, request, sink, session) @@ -2390,7 +2408,14 @@ impl Scheduler { .warnings .record(job_id, &unavailable.server, &unavailable.reason); } - self.record_run_cost(job_id, &cost_session, agent, model.as_deref(), &report); + self.record_run_cost( + job_id, + &cost_session, + agent, + model.as_deref(), + &report, + openrouter_key, + ); match report.head { Some(head) if matches!(report.event, Event::QuickReviewed { .. }) => { let Event::QuickReviewed { score, review, .. } = report.event else { @@ -2479,6 +2504,50 @@ impl Scheduler { } } + /// Reads what `OpenRouter` charged for the generations `report` shows with + /// `key`, in the background so the run's next step never waits for it, and + /// records the sum. When the cost cannot be read, the run adds no cost and + /// the log says so. + fn record_openrouter_cost(&self, job_id: i64, report: &RunReport, key: Option) { + let tokens = report.token_usage.map(|usage| { + format!( + "{} input tokens, {} output tokens", + usage.input_tokens, usage.output_tokens + ) + }); + let store = Arc::clone(&self.store); + let costs = Arc::clone(&self.costs); + let ids = report.generation_ids.clone(); + tokio::spawn(async move { + let total = match &key { + Some(key) => costs.total(key, &ids).await, + None => None, + }; + let mut text = match total { + Some(total) => match store.add_cost(job_id, total, false) { + Ok(()) => format!( + "OpenRouter run finished, {} charged by OpenRouter", + format_cost(total) + ), + Err(err) => { + tracing::error!("job {job_id}: {err}"); + return; + } + }, + None => "OpenRouter run finished. The cost could not be read from \ + OpenRouter and is not counted" + .to_owned(), + }; + if let Some(tokens) = tokens { + let _ = write!(text, ". {tokens}"); + } + text.push('.'); + if let Err(err) = store.append_factory_log(job_id, &text) { + tracing::error!("job {job_id}: {err}"); + } + }); + } + /// Records the cost of a finished agent run and notes it on the job log. A /// run that reports a dollar figure, such as Claude's, reports the total of /// the session whose factory UUID is `session`, so the run records the @@ -2488,7 +2557,9 @@ impl Scheduler { /// toward the job and project totals and is marked estimated, and with no row /// for the model, or no model at all, the run adds no cost and the log names /// the model. The token counts go to the log either way. A Copilot run adds - /// no cost at all. + /// no cost at all. An `OpenRouter` run records what `OpenRouter` charged for + /// the generations its output showed, read with `openrouter_key` in the + /// background, so the run's next step never waits for it. fn record_run_cost( &self, job_id: i64, @@ -2496,6 +2567,7 @@ impl Scheduler { agent: Agent, model: Option<&str>, report: &RunReport, + openrouter_key: Option, ) { if agent == Agent::Local { // A local model has no price. The run adds a row of zero, so the job @@ -2517,16 +2589,7 @@ impl Scheduler { return; } if agent == Agent::OpenRouter { - let mut text = "OpenRouter run finished".to_owned(); - if let Some(usage) = report.token_usage { - let _ = write!( - text, - ". {} input tokens, {} output tokens", - usage.input_tokens, usage.output_tokens - ); - } - text.push('.'); - self.note(job_id, &text); + self.record_openrouter_cost(job_id, report, openrouter_key); return; } if agent == Agent::Copilot { diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index b099e25..dd553da 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -612,10 +612,11 @@ pub struct ProjectTotals { } /// Selects the `job_costs` rows to show as a cost: a positive total, or a zero -/// total of a job that ran a worker on Local. Another zero row reads as no cost. +/// total of a job that ran a worker on Local or `OpenRouter`, whose cost is +/// known to be nothing, such as a `:free` model. Another zero row reads as no cost. const SHOWN_COST: &str = "(c.usd > 0 OR EXISTS ( SELECT 1 FROM sessions s - WHERE s.job_id = c.job_id AND s.agent = 'local' AND s.local_cli IS NOT NULL))"; + WHERE s.job_id = c.job_id AND s.agent IN ('local', 'openrouter') AND s.local_cli IS NOT NULL))"; /// One model's Codex prices, in USD per million tokens. The factory estimates a /// Codex run's cost from the row for the model it ran, since Codex reports token diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index 78537f8..46cfea2 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -1695,7 +1695,29 @@ async fn a_job_that_only_ran_on_local_shows_zero_dollars_with_no_estimate_mark() } #[tokio::test] -async fn a_started_openrouter_session_leaves_a_subscription_zero_cost_as_a_dash() { +async fn an_openrouter_job_shows_what_openrouter_charged_with_no_estimate_mark() { + let dashboard = dashboard(); + let id = dashboard.new_job().await; + dashboard + .store + .session_uuid(id, Session::Planning, Agent::OpenRouter) + .unwrap(); + dashboard + .store + .record_session_provider_cli(id, Session::Planning, Cli::ClaudeCode) + .unwrap(); + dashboard.store.add_cost(id, 0.10 + 0.25, false).unwrap(); + + let page = dashboard.get(&format!("/jobs/{id}")).await; + assert!( + page.body + .contains("$0.35") + ); + assert!(!page.body.contains("≈")); +} + +#[tokio::test] +async fn an_openrouter_job_whose_generations_were_free_shows_zero_dollars() { let dashboard = dashboard(); let id = dashboard.new_job().await; dashboard.store.add_cost(id, 0.0, false).unwrap(); @@ -1711,8 +1733,11 @@ async fn a_started_openrouter_session_leaves_a_subscription_zero_cost_as_a_dash( let page = dashboard.get(&format!("/jobs/{id}")).await; assert!( page.body - .contains("–") + .contains("$0.00") ); + let index = dashboard.get("/").await; + assert!(index.body.contains("$0.00")); + assert!(!page.body.contains("≈")); } #[tokio::test] diff --git a/crates/factory-server/tests/openrouter_http.rs b/crates/factory-server/tests/openrouter_http.rs index 74eb510..8dfacf4 100644 --- a/crates/factory-server/tests/openrouter_http.rs +++ b/crates/factory-server/tests/openrouter_http.rs @@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex}; use axum::{Router, http::HeaderMap, http::Method, routing::any}; -use factory_server::{HttpOpenRouterApi, OpenRouterApi}; +use factory_server::{GenerationError, HttpOpenRouterApi, OpenRouterApi}; #[tokio::test] async fn the_client_sends_one_bearer_get_to_the_key_endpoint() { @@ -38,3 +38,61 @@ async fn the_client_sends_one_bearer_get_to_the_key_endpoint() { vec![(Method::GET, Some("Bearer sk-or-v1-key".to_owned()))] ); } + +#[tokio::test] +async fn the_client_reads_a_generations_total_cost_and_treats_a_404_as_not_ready() { + let seen = Arc::new(Mutex::new(Vec::<(String, Option)>::new())); + let log = Arc::clone(&seen); + let app = Router::new().route( + "/api/v1/generation", + axum::routing::get( + move |axum::extract::Query(query): axum::extract::Query< + std::collections::HashMap, + >, + headers: HeaderMap| { + let log = Arc::clone(&log); + async move { + let id = query["id"].clone(); + let auth = headers + .get("authorization") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + log.lock().unwrap().push((id.clone(), auth)); + match id.as_str() { + "gen-1" => ( + axum::http::StatusCode::OK, + r#"{"data":{"total_cost":0.125}}"#, + ), + "gen-empty" => (axum::http::StatusCode::OK, r#"{"data":{}}"#), + "gen-denied" => (axum::http::StatusCode::FORBIDDEN, ""), + _ => (axum::http::StatusCode::NOT_FOUND, ""), + } + } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/api", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let api = HttpOpenRouterApi::with_base_url(&url); + + assert_eq!(api.generation("gen-1", "sk-or-v1-key").await, Ok(0.125)); + assert_eq!( + api.generation("gen-2", "sk-or-v1-key").await, + Err(GenerationError::NotReady) + ); + assert_eq!( + api.generation("gen-empty", "sk-or-v1-key").await, + Err(GenerationError::NotReady) + ); + let denied = api + .generation("gen-denied", "sk-or-v1-key") + .await + .unwrap_err(); + assert!(!denied.retryable()); + assert!(!denied.to_string().contains("sk-or")); + assert_eq!( + seen.lock().unwrap()[0], + ("gen-1".to_owned(), Some("Bearer sk-or-v1-key".to_owned())) + ); +} diff --git a/crates/factory-server/tests/openrouter_run.rs b/crates/factory-server/tests/openrouter_run.rs index 32133fb..a9c8e24 100644 --- a/crates/factory-server/tests/openrouter_run.rs +++ b/crates/factory-server/tests/openrouter_run.rs @@ -12,10 +12,11 @@ use factory_runner::{ WorkerConfig, }; use factory_server::{ - AccountSource, AgentRegistry, AgentRequest, ClaudeToken, CodexLogin, Executor, Forges, GhRepos, - HttpLocalServerProbe, KeyOwner, LocalSecrets, MASTER_KEY_LEN, ModelsError, OpenRouterApi, - OpenRouterKeyFuture, OpenRouterModelsFuture, PlanUsageCache, PodmanExecutor, ProviderRequest, - SecretStore, Settings, Store, + AccountSource, AgentRegistry, AgentRequest, ClaudeToken, CodexLogin, Executor, Forges, + GenerationError, GhRepos, HttpLocalServerProbe, KeyOwner, LocalSecrets, MASTER_KEY_LEN, + ModelsError, OpenRouterApi, OpenRouterGenerationFuture, OpenRouterKeyFuture, + OpenRouterModelsFuture, PlanUsageCache, PodmanExecutor, ProviderRequest, SecretStore, Settings, + Store, }; mod support; @@ -36,6 +37,10 @@ impl OpenRouterApi for FakeApi { self.seen.lock().unwrap().push(key.to_owned()); Box::pin(std::future::ready(self.answer.clone())) } + + fn generation<'a>(&'a self, _id: &'a str, _key: &'a str) -> OpenRouterGenerationFuture<'a> { + Box::pin(std::future::ready(Err(GenerationError::NotReady))) + } } struct Fixture { diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index 458047c..0a7b5a5 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -15,18 +15,89 @@ use factory_runner::{ }; use factory_server::{ AccountSource, Accounts, AgentRegistry, AgentRequest, ChecksRequest, ClaudeToken, CodexLogin, - CodexPrice, Executor, FACTORY_REQUESTER, ForgeTokenOwner, Forges, GhRepos, + CodexPrice, Executor, FACTORY_REQUESTER, ForgeTokenOwner, Forges, GenerationError, GhRepos, HttpLocalServerProbe, HttpOpenRouterApi, IgnoredCommenter, JobFile, LocalSecrets, LogSink, - MASTER_KEY_LEN, McpProjectSettings, McpRuntime, McpStages, McpTransport, McpWarnings, Owner, - PlanUsageCache, PodmanExecutor, PrerequisiteEdit, Project, ProjectForge, Projects, - PublishRequest, Published, ReadyAction, Rebase, RenovateAgent, RenovateWatchRequest, - RerunRequest, RunTokens, Scheduler, SecretRef, SecretStore, SessionSink, Settings, StageAgents, - StageEfforts, StageModels, Store, SummaryRequest, UnavailableSecrets, UpstreamCredential, - WatchReport, WatchRequest, WorkerSlots, credential_failure, format_cost, ready_action, - waiting_event, + MASTER_KEY_LEN, McpProjectSettings, McpRuntime, McpStages, McpTransport, McpWarnings, + ModelsError, OpenRouterApi, OpenRouterCosts, OpenRouterGenerationFuture, OpenRouterKeyFuture, + OpenRouterModelsFuture, Owner, PlanUsageCache, PodmanExecutor, PrerequisiteEdit, Project, + ProjectForge, Projects, PublishRequest, Published, ReadyAction, Rebase, RenovateAgent, + RenovateWatchRequest, RerunRequest, RunTokens, Scheduler, SecretRef, SecretStore, SessionSink, + Settings, StageAgents, StageEfforts, StageModels, Store, SummaryRequest, UnavailableSecrets, + UpstreamCredential, WatchReport, WatchRequest, WorkerSlots, credential_failure, format_cost, + ready_action, waiting_event, }; use tokio::sync::{Notify, Semaphore}; +/// Answers a generation lookup from a table. An id with no entry is not known +/// yet, as `OpenRouter` answers right after a run. +#[derive(Default)] +struct FakeGenerations { + costs: Mutex>, + keys: Mutex>, +} + +impl OpenRouterApi for FakeGenerations { + fn models<'a>(&'a self, _key: Option<&'a str>) -> OpenRouterModelsFuture<'a> { + Box::pin(async { Err(ModelsError::Connect) }) + } + + fn check_key<'a>(&'a self, _key: &'a str) -> OpenRouterKeyFuture<'a> { + Box::pin(async { Ok(()) }) + } + + fn generation<'a>(&'a self, id: &'a str, key: &'a str) -> OpenRouterGenerationFuture<'a> { + Box::pin(async move { + self.keys.lock().unwrap().push(key.to_owned()); + self.costs + .lock() + .unwrap() + .iter() + .find(|(known, _)| known == id) + .map(|(_, cost)| *cost) + .ok_or(GenerationError::NotReady) + }) + } +} + +/// Lookups that answer from `table` and ask again after a millisecond. +fn fake_costs(table: &[(&str, f64)]) -> (OpenRouterCosts, Arc) { + let api = Arc::new(FakeGenerations::default()); + *api.costs.lock().unwrap() = table + .iter() + .map(|(id, cost)| ((*id).to_owned(), *cost)) + .collect(); + let costs = OpenRouterCosts::with_delays( + Arc::clone(&api) as Arc, + vec![Duration::from_millis(1); 3], + ); + (costs, api) +} + +/// Lookups that find nothing. +fn no_costs() -> OpenRouterCosts { + fake_costs(&[]).0 +} + +/// Waits for the background cost lookup of an `OpenRouter` run to log its +/// outcome, and returns that line. +async fn openrouter_finished(store: &Store, id: i64, count: usize) -> Vec { + for _ in 0..500 { + let lines = finished_lines_with(store, id, "OpenRouter run finished"); + if lines.len() >= count { + return lines; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("the OpenRouter cost lookup logged nothing"); +} + +fn finished_lines_with(store: &Store, id: i64, prefix: &str) -> Vec { + log_texts(store, id) + .into_iter() + .filter(|text| text.starts_with(prefix)) + .collect() +} + fn ready() -> PrDescription { PrDescription { title: "maestrod: add a reboot endpoint".into(), @@ -46,6 +117,9 @@ struct FakeExecutor { /// The token usage each run reports instead of a dollar cost, the way a /// Codex run does. A run with none queued reports no usage, as Claude does. token_usages: Mutex>, + /// The generation ids each run's output shows, the way an `OpenRouter` run's + /// does. A run with none shows no id. + generations: Mutex>>, /// The MCP servers each run reports as not connected in its init line. unavailable: Mutex>>, tool_calls: Mutex>>, @@ -131,6 +205,7 @@ impl FakeExecutor { requests: Mutex::new(Vec::new()), costs: Mutex::new(VecDeque::new()), token_usages: Mutex::new(VecDeque::new()), + generations: Mutex::new(VecDeque::new()), unavailable: Mutex::new(VecDeque::new()), tool_calls: Mutex::new(VecDeque::new()), sessions: Mutex::new(VecDeque::new()), @@ -208,6 +283,14 @@ impl FakeExecutor { self.sessions.lock().unwrap().push_back(id.to_owned()); } + /// Makes the next run's output show the generation ids `ids`. + fn report_generations(&self, ids: &[&str]) { + self.generations + .lock() + .unwrap() + .push_back(ids.iter().map(|id| (*id).to_owned()).collect()); + } + fn requests(&self) -> Vec { self.requests.lock().unwrap().clone() } @@ -283,7 +366,12 @@ impl Executor for FakeExecutor { .unwrap_or_default(), credential: None, token_usage, - generation_ids: Vec::new(), + generation_ids: self + .generations + .lock() + .unwrap() + .pop_front() + .unwrap_or_default(), head: self.checkout_head.lock().unwrap().clone(), } } @@ -705,6 +793,7 @@ fn setup_in( PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); (store, executor, scheduler) } @@ -760,6 +849,7 @@ fn setup_mcp( PathBuf::new(), runtime, accounts(&store), + no_costs(), ); (store, executor, scheduler, tokens) } @@ -1160,6 +1250,7 @@ async fn a_project_onboarded_while_running_is_picked_up() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); let id = store @@ -2169,6 +2260,7 @@ async fn a_project_without_checks_publishes_unchecked() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); drop(scheduler); for event in [ @@ -2208,6 +2300,7 @@ async fn an_edited_checks_command_applies_to_a_job_created_before_the_edit() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); store .create_project( @@ -2304,6 +2397,7 @@ async fn a_project_on_an_unknown_forge_fails_its_job_and_leaves_the_others_runni PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); drop(scheduler); let odd = store.create("odd", "alice", "x").unwrap(); @@ -2370,6 +2464,7 @@ async fn a_failed_publish_waits_before_it_is_tried_again() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); step(&fresh).await; assert_eq!(executor.published.lock().unwrap().len(), 2); @@ -2409,6 +2504,7 @@ async fn a_project_that_moves_to_an_unknown_forge_stops_a_job_in_a_factory_turn( PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); step(&odd).await; @@ -3114,6 +3210,7 @@ mod purge { data.path().to_owned(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); let db = rusqlite::Connection::open(&path).unwrap(); Fixture { @@ -3608,6 +3705,7 @@ async fn a_project_does_not_use_the_models_of_another() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); store .save_project_models("maestro", &models("maestro-c", "", "", "")) @@ -4324,6 +4422,7 @@ async fn a_job_from_before_fresh_sessions_resumes_its_planning_session() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); let id = store .create("maestro", "alice", "Add a reboot button") @@ -4676,10 +4775,7 @@ async fn an_init_line_failure_records_one_warning_and_the_run_goes_on() { ); // The run did not fail: it reached the clarify questions, so the warning is // only a note. - assert!(matches!( - store.get(id).unwrap().job.stage(), - Stage::Clarifying - )); + assert_eq!(store.get(id).unwrap().job.stage(), &Stage::Clarifying); } #[tokio::test] @@ -4769,6 +4865,7 @@ fn setup_two_projects( PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); (store, executor, scheduler) } @@ -5096,6 +5193,7 @@ async fn an_edited_queued_job_runs_clarify_with_the_new_text_and_attachments() { data.path().to_owned(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); let id = store @@ -6057,6 +6155,7 @@ async fn discovery_makes_one_job_per_renovate_pull_request() { PathBuf::new(), mcp_runtime(store).0, accounts(store), + no_costs(), ) }; @@ -6139,6 +6238,7 @@ async fn salsa_discovery_skips_a_project_with_renovate_on_and_no_author() { PathBuf::new(), mcp_runtime(&store).0, Accounts::new(Arc::clone(&store), secrets as Arc, forges), + no_costs(), ); step(&scheduler).await; @@ -6214,6 +6314,7 @@ async fn salsa_discovery_lists_by_the_renovate_account_and_github_by_none() { PathBuf::new(), mcp_runtime(&store).0, accounts, + no_costs(), ); secrets .put_forge_token( @@ -6312,6 +6413,7 @@ fn forgejo_discovery( PathBuf::new(), mcp_runtime(&store).0, Accounts::new(Arc::clone(&store), secrets as Arc, forges), + no_costs(), ); (store, executor, scheduler) } @@ -7049,6 +7151,7 @@ async fn a_restart_keeps_the_count_of_checks_that_could_not_run() { PathBuf::new(), mcp_runtime(&store).0, accounts(&store), + no_costs(), ); step(&fresh).await; step(&fresh).await; @@ -8225,6 +8328,18 @@ fn setup_local( Arc, Arc>, Arc, +) { + setup_local_with(respond, no_costs()) +} + +fn setup_local_with( + respond: impl Fn(&AgentRequest) -> Event + Send + Sync + 'static, + costs: OpenRouterCosts, +) -> ( + Arc, + Arc, + Arc>, + Arc, ) { let store = Arc::new(Store::open_in_memory().unwrap()); let secrets = Arc::new(LocalSecrets::new(&[1; MASTER_KEY_LEN], Arc::clone(&store))); @@ -8258,6 +8373,7 @@ fn setup_local( PathBuf::new(), runtime, accounts(&store), + costs, ); store .save_local_settings(Some(LOCAL_URL), factory_core::Cli::Codex, 10) @@ -8843,7 +8959,19 @@ fn setup_openrouter( Arc>, Arc, ) { - let (store, executor, scheduler, secrets) = setup_local(respond); + setup_openrouter_with(respond, no_costs()) +} + +fn setup_openrouter_with( + respond: impl Fn(&AgentRequest) -> Event + Send + Sync + 'static, + costs: OpenRouterCosts, +) -> ( + Arc, + Arc, + Arc>, + Arc, +) { + let (store, executor, scheduler, secrets) = setup_local_with(respond, costs); store .save_project_agents( "maestro", @@ -9153,24 +9281,6 @@ async fn one_job_runs_a_local_stage_and_an_openrouter_stage_each_with_its_own_li assert!(log.iter().any(|text| text.starts_with("OpenRouter run on"))); } -#[tokio::test] -async fn an_openrouter_run_adds_no_cost_row() { - let (store, executor, scheduler, secrets) = setup_openrouter(|_| questions()); - secrets.set_openrouter_key("factory-key").unwrap(); - executor.costs.lock().unwrap().push_back(Some(4.2)); - executor.release(1); - let id = store.create("maestro", "alice", "Add a button").unwrap(); - step(&scheduler).await; - - assert_eq!(store.recorded_cost(id).unwrap(), None); - assert_eq!(store.cost_usd(id).unwrap(), 0.0); - assert!( - log_texts(&store, id) - .iter() - .any(|text| text.starts_with("OpenRouter run finished")) - ); -} - #[tokio::test] async fn a_change_to_the_worker_packages_reaches_the_next_run() { let (store, executor, scheduler) = setup_two_projects(|_| questions()); @@ -10225,3 +10335,114 @@ async fn conflict_on_stack( ); rebase } + +fn clarify_after_answer(request: &AgentRequest) -> Event { + if request.prompt.contains("answered") { + Event::Agent(AgentResult::Clarified) + } else { + questions() + } +} + +#[tokio::test] +async fn an_openrouter_run_records_the_cost_openrouter_charged() { + let (costs, api) = fake_costs(&[("gen-1", 0.10), ("gen-2", 0.25), ("gen-3", 0.5)]); + let (store, executor, scheduler, secrets) = setup_openrouter_with(clarify_after_answer, costs); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.report_generations(&["gen-1", "gen-2"]); + // The dollar figure the CLI reports and the token counts are ignored. + executor.costs.lock().unwrap().push_back(Some(9.0)); + executor + .token_usages + .lock() + .unwrap() + .push_back(codex_usage()); + executor.release(2); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + step(&scheduler).await; + + let lines = openrouter_finished(&store, id, 1).await; + assert_eq!( + lines[0], + "OpenRouter run finished, $0.35 charged by OpenRouter. 1000 input tokens, 500 output \ + tokens." + ); + assert!((store.cost_usd(id).unwrap() - 0.35).abs() < 1e-9); + assert!((store.project_totals("maestro").unwrap().usd - 0.35).abs() < 1e-9); + assert!(!store.has_estimated_cost(id).unwrap()); + assert!( + api.keys + .lock() + .unwrap() + .iter() + .all(|key| key == "factory-key") + ); + + // The resumed run counts only its own generation. + store.apply(id, Event::Answer(vec!["rpi5".into()])).unwrap(); + executor.report_generations(&["gen-3"]); + step(&scheduler).await; + openrouter_finished(&store, id, 2).await; + assert!((store.cost_usd(id).unwrap() - 0.85).abs() < 1e-9); +} + +#[tokio::test] +async fn an_openrouter_run_with_an_unreadable_generation_adds_no_cost_and_still_applies_its_event() +{ + let (costs, _) = fake_costs(&[("gen-1", 0.10)]); + let (store, executor, scheduler, secrets) = setup_openrouter_with(|_| questions(), costs); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.report_generations(&["gen-1", "gen-missing"]); + executor + .token_usages + .lock() + .unwrap() + .push_back(codex_usage()); + executor.release(1); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + step(&scheduler).await; + + let lines = openrouter_finished(&store, id, 1).await; + assert_eq!( + lines[0], + "OpenRouter run finished. The cost could not be read from OpenRouter and is not \ + counted. 1000 input tokens, 500 output tokens." + ); + assert_eq!(store.recorded_cost(id).unwrap(), None); + assert_eq!(store.project_totals("maestro").unwrap().usd, 0.0); + assert_eq!(store.get(id).unwrap().job.stage(), &Stage::Clarifying); +} + +#[tokio::test] +async fn an_openrouter_run_that_shows_no_generation_id_adds_no_cost() { + let (store, executor, scheduler, secrets) = setup_openrouter(|_| questions()); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.release(1); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + step(&scheduler).await; + + let lines = openrouter_finished(&store, id, 1).await; + assert_eq!( + lines[0], + "OpenRouter run finished. The cost could not be read from OpenRouter and is not counted." + ); + assert_eq!(store.recorded_cost(id).unwrap(), None); +} + +#[tokio::test] +async fn an_openrouter_generation_that_cost_nothing_records_a_zero_row() { + let (costs, _) = fake_costs(&[("gen-free", 0.0)]); + let (store, executor, scheduler, secrets) = setup_openrouter_with(|_| questions(), costs); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.report_generations(&["gen-free"]); + executor.release(1); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + step(&scheduler).await; + + let lines = openrouter_finished(&store, id, 1).await; + assert_eq!( + lines[0], + "OpenRouter run finished, $0.00 charged by OpenRouter." + ); + assert_eq!(store.recorded_cost(id).unwrap(), Some(0.0)); +} diff --git a/crates/factory-server/tests/support/copilot_harness.rs b/crates/factory-server/tests/support/copilot_harness.rs index 9af2751..8a8fa0e 100644 --- a/crates/factory-server/tests/support/copilot_harness.rs +++ b/crates/factory-server/tests/support/copilot_harness.rs @@ -12,11 +12,11 @@ use axum::body::Body; use axum::http::{Request, StatusCode, header}; use factory_runner::{Account, GitHub}; use factory_server::{ - AgentRegistry, ClaudeToken, CodexLogin, DeviceLogin, Forges, HttpForgejoProbe, + AgentRegistry, ClaudeToken, CodexLogin, DeviceLogin, Forges, GenerationError, HttpForgejoProbe, HttpLocalServerProbe, LocalSecrets, LoginProcess, LoginSpawner, LoginSpec, MASTER_KEY_LEN, - McpChecker, ModelsError, OpenRouterApi, OpenRouterKeyFuture, OpenRouterModel, - OpenRouterModelsFuture, PlanUsageCache, Projects, RepoChecker, RepoReport, SecretStore, Store, - USER_HEADER, UnavailableSecrets, WorkerSlots, app_with_forgejo_probe, + McpChecker, ModelsError, OpenRouterApi, OpenRouterGenerationFuture, OpenRouterKeyFuture, + OpenRouterModel, OpenRouterModelsFuture, PlanUsageCache, Projects, RepoChecker, RepoReport, + SecretStore, Store, USER_HEADER, UnavailableSecrets, WorkerSlots, app_with_forgejo_probe, }; use http_body_util::BodyExt; use tokio::sync::Notify; @@ -165,6 +165,10 @@ impl OpenRouterApi for FakeOpenRouter { fn check_key<'a>(&'a self, _key: &'a str) -> OpenRouterKeyFuture<'a> { Box::pin(std::future::ready(Ok(()))) } + + fn generation<'a>(&'a self, _id: &'a str, _key: &'a str) -> OpenRouterGenerationFuture<'a> { + Box::pin(std::future::ready(Err(GenerationError::NotReady))) + } } pub struct NoRepos; diff --git a/docs/design.md b/docs/design.md index e606a83..30be2aa 100644 --- a/docs/design.md +++ b/docs/design.md @@ -80,7 +80,7 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | Merged job cleanup | A merged job is final: no event moves it out of `Merged`, it has no next command, and Retry applies only to failed jobs, so nothing reads its checkout or session files again. On every job-loop pass, after expiry, the factory deletes `/jobs//work`, `/jobs//claude` and `/jobs//codex` for each merged job that still has any of them. `work/` is the git checkout the workers and checks run in, which holds build output such as cargo's `target/`; `claude/` is the Claude Code config directory with the session files `--resume` reads, and `codex/` is Codex's `CODEX_HOME` with its session rollout files. On moon the merged jobs' directories had grown to about 50 GB of the 74 GB free disk, which this frees. The check runs every pass, not only on the transition into `Merged`, so it also cleans jobs merged before this change and retries a deletion that failed. The pass skips a merged job while the scheduler still holds an unfinished task for it. A deletion error is logged with the job id and the loop goes on, the way expiry does, and a directory already gone counts as success. After the directories are gone the factory appends one line to the job log saying it removed the checkout and session files to free disk space, written only on the pass that deleted something, so a job does not collect the line on every pass. Everything else stays: the job row and its rows in the logs, events, costs, sessions, images, files and PR watermark tables, and the `images/` and `files/` directories the job page serves, so the page, its attachments and the board look the same as before. Failed and cancelled jobs keep their directories, because Retry resumes a failed job from them; a cancelled job could get the same treatment in a later change. | | Capacity | At most 2 worker containers at a time. Each worker gets `--memory 3g --cpus 4`. A job waiting for you holds no worker, and neither does a request that waits for other jobs to merge, see Request prerequisites. The limit, image, memory and CPUs are settings stored in SQLite, read by the job loop on every pass, so a settings page can change them without a restart. The scheduler records which job holds which numbered slot, and since when, in a `WorkerSlots` handle it shares with the dashboard. A worker run takes the lowest free slot number when it starts and frees it when it ends or the job no longer wants it. Checks run in a worker and take a slot too. Factory steps such as a push or a pull request watch run in the factory process and take none. The board shows one tile per slot above the request bar, as many as the worker limit. A busy tile links to the job and shows its stage and how long it has held the slot. A job of another project shows that project's name, because the slots are shared by every project. An idle tile says idle. When the factory runs without podman workers, every tile is idle. | | Job page timeline | The job page has two columns. The left one holds the status card, the request, the spec, the plan, the review passes and the log. The right one holds the timeline, which replaced the nine-step tracker under the title. In the two-column layout the timeline stays in view under the top bar as the left column scrolls, and scrolls on its own when it is taller than the window. Below 900px the columns stack, with the timeline between the status card and the request. The timeline reads the job history, see Job history. It lists the four planning steps, then a group for each planned pull request with its four steps, then merged. A pull request goes back through verifying, pr-open and ci-and-review after each fix, so each step adds up every visit: it shows the time the job first entered it, the time spent in it over all visits, and the API cost of the runs in it. Under a step, timed notes list what happened in it: questions and answers, requested changes, failed checks and CI, CI reruns, conflicts, review comments, LLM review verdicts, failures, retries and a cancel. The last 8 notes show and older ones collapse into one line. A gate shows `✓ approved` with its time once approved, and a `✋ approval` badge until then. The publish gate sits on verifying and applies only before a pull request's first push. The step the job is in shows who acts: the model of the agent run, from the project's models as the next run would use them, with what the agent is doing; `waiting for you`; or `factory`. A failed job marks the step it failed in and shows the reason. Each pull request group is a `
` element, so it works without JavaScript. It starts open while a step in it is running or failed, and its summary shows the number, the title and, once done, the total time and cost. A poll swap resets a group the reader opened or closed. A job from before the history has no times or costs: the steps before its current one show as done without them. A legacy failed job with no history shows its reason under the steps. | -| Job cost | Each job has a running total of the API cost of its agent runs, in USD. It lives in the `job_costs` table in SQLite, one row per job, so a job from before the table existed has no row and reads 0. `Scheduler::record_run_cost` adds the cost after each run: a Claude run reports `total_cost_usd`, the cost of its whole session so far, which keeps counting across `--resume`. The `sessions` row keeps the last total in `cost_usd`, and the run adds the increase over it. A total below the stored one means Claude started the session over, so the run adds the whole total. A session from before the column existed has no stored total, so its next run adds its whole total once. Before this rule the factory added every total as it was, so a resumed session counted its earlier runs again: job 41 showed $20.90 for its ci-and-review stage, which cost $1.18. A run that reports no figure adds nothing. A Copilot run adds no cost row and no estimate, since Copilot bills in credits the factory does not price. `Scheduler::record_run_cost` writes one job log line per Copilot run, "Copilot runs are not counted in the cost", and a job that ran only on Copilot shows "–". A Codex run reports token counts and no dollar figure, so the factory estimates it from a price table, see below. A cancelled or failed job keeps its total. `format_cost` formats it as `$1.23`, for the log and the job page. The job page shows the total as a pill badge on the title row, right-aligned and vertically centred with the heading, out of the meta line. When any of the job's cost rows is an estimate the pill carries a `≈` and a title that says the total includes an estimate for Codex runs. A job with no recorded cost shows "–". The job board shows it on each card. The stats strip shows the project total, see Project totals. **Codex estimate.** The `codex_prices` table in SQLite holds one row per model id with three USD prices per million tokens: input, cached input and output. The table starts empty, and the Codex settings page adds, edits and deletes a row, so a price change needs no code change or deploy. A Codex run sums the `usage` of every `turn.completed` line. `cost::codex_cost` reads the row for the model the run passed and bills the uncached input, `input_tokens` minus `cached_input_tokens`, at the input price, the cached input at the cached price, and `output_tokens`, which already counts `reasoning_output_tokens`, at the output price. The estimate goes through `Store::add_cost` with its `cost` row in `job_events` marked `estimated`, so it counts in the job total and the project totals like a reported cost, and `Store::has_estimated_cost` tells the job page to flag the pill. When the run passed no model, or the model has no price row, the run adds no cost and the job log names the model; the run's token counts go to the log either way. A price change applies to runs after it, and recorded costs stay as they are. A Local run adds a $0 row whatever the CLI reports and never uses the price table, even for a model id it lists; a $0 row shows `$0.00` only for a job that started a Local worker, and any other $0 row, such as a Claude or Codex run that cost nothing, shows a dash. | +| Job cost | Each job has a running total of the API cost of its agent runs, in USD. It lives in the `job_costs` table in SQLite, one row per job, so a job from before the table existed has no row and reads 0. `Scheduler::record_run_cost` adds the cost after each run: a Claude run reports `total_cost_usd`, the cost of its whole session so far, which keeps counting across `--resume`. The `sessions` row keeps the last total in `cost_usd`, and the run adds the increase over it. A total below the stored one means Claude started the session over, so the run adds the whole total. A session from before the column existed has no stored total, so its next run adds its whole total once. Before this rule the factory added every total as it was, so a resumed session counted its earlier runs again: job 41 showed $20.90 for its ci-and-review stage, which cost $1.18. A run that reports no figure adds nothing. A Copilot run adds no cost row and no estimate, since Copilot bills in credits the factory does not price. `Scheduler::record_run_cost` writes one job log line per Copilot run, "Copilot runs are not counted in the cost", and a job that ran only on Copilot shows "–". A Codex run reports token counts and no dollar figure, so the factory estimates it from a price table, see below. A cancelled or failed job keeps its total. `format_cost` formats it as `$1.23`, for the log and the job page. The job page shows the total as a pill badge on the title row, right-aligned and vertically centred with the heading, out of the meta line. When any of the job's cost rows is an estimate the pill carries a `≈` and a title that says the total includes an estimate for Codex runs. A job with no recorded cost shows "–". The job board shows it on each card. The stats strip shows the project total, see Project totals. **Codex estimate.** The `codex_prices` table in SQLite holds one row per model id with three USD prices per million tokens: input, cached input and output. The table starts empty, and the Codex settings page adds, edits and deletes a row, so a price change needs no code change or deploy. A Codex run sums the `usage` of every `turn.completed` line. `cost::codex_cost` reads the row for the model the run passed and bills the uncached input, `input_tokens` minus `cached_input_tokens`, at the input price, the cached input at the cached price, and `output_tokens`, which already counts `reasoning_output_tokens`, at the output price. The estimate goes through `Store::add_cost` with its `cost` row in `job_events` marked `estimated`, so it counts in the job total and the project totals like a reported cost, and `Store::has_estimated_cost` tells the job page to flag the pill. When the run passed no model, or the model has no price row, the run adds no cost and the job log names the model; the run's token counts go to the log either way. A price change applies to runs after it, and recorded costs stay as they are. A Local run adds a $0 row whatever the CLI reports and never uses the price table, even for a model id it lists. An OpenRouter run records the cost OpenRouter charged: after the run the server reads `GET /api/v1/generation?id=` with the run's key for each generation id the run's output showed, and adds the sum of `total_cost` through `Store::add_cost`, not marked estimated. The key's total `usage` is not used, because another run or any outside use of the same key would be counted. There is no estimate from token counts, so a run whose ids stay unreadable adds no cost and the job shows a dash if it has no other. A $0 row shows `$0.00` only for a job that started a Local or OpenRouter worker, which includes a fetched `:free` cost of $0, and any other $0 row, such as a Claude or Codex run that cost nothing, shows a dash. | | Job history | The `job_events` table in SQLite keeps what happened to each job, one row per entry, oldest first by id. `Store::apply_in` writes a row in the same transaction as every event it applies, except an `Event::RenovateObserved` that leaves the job unchanged, which writes nothing so the timeline does not grow on each look, so the history and the stored job cannot disagree, and a rejected event writes nothing. A row has the time, the event name, and the stage, pull request index and turn the event left the job in. `Store::create` writes a `created` row, and `Store::add_cost` writes a `cost` row with the run's cost in USD against the stage the run ran in, because the scheduler adds the cost before it applies the run's event. `Store::record_mcp_tool_call` writes an `mcp-tool-call` row the same way, against the stage the job is in, for each MCP call the proxy forwards, see Job MCP tool calls. A failed agent or reviewer run and a CI rerun keep their reason in the row. The names come from `Stage::name`, `Turn::name` and `Event::name` in `factory-core`, such as `implementing`, `agent:fix-checks` and `review-approved`. They are stored, so renaming one breaks the history of stored jobs. A job from before the table has entries only from the table's first deploy on. Job expiry deletes a job's rows with the job. The job page timeline reads it. The fix events store as `fix-started`, `fix-ended`, `rebase-requested`, `rebase-skipped` and `rebase-failed`. | | Project totals | The `project_totals` table in SQLite keeps one row per project with the total API cost, the number of jobs created and the number of jobs merged. The totals outlive the jobs: the expiry loop deletes a job and leaves them alone. Each counter changes when its event happens. A job counts as created when the store inserts it, so cancelled and failed jobs count as created and nothing more. A job counts as merged when it first reaches the Merged stage, once per job however many pull requests it had, and not when one of its pull requests merges. A job that fails or is cancelled after some pull requests merged is not merged. Cost adds the amount of each agent run, next to the job's own total in `job_costs`. Jobs from before the table existed are not counted, so the totals start at zero. `Store::project_totals` reads them, and a project with no row reads 0. The index page shows them on one line below the board, for the selected project: total API cost, jobs created, jobs merged, merge rate and average cost per merged job. `merge_fraction` computes the merge rate as merged divided by created, and returns 0.0 when nothing was created. The line shows it rounded to a whole percent. The average is total cost divided by merged, formatted with `format_cost`. Created and merged show "–" at zero. The merge rate shows "–" with no jobs created, and the average shows "–" with no merged job, so nothing divides by zero. Total cost shows `$0.00` at zero. | | Job retry | A job that failed because it used up its 5 failed check or CI rounds, because its local checks could not run 5 times in a row, or because an agent run failed, can be resumed from its job page. The failure card shows a Retry button, which posts to `POST /jobs/{id}/retry` (an optional project, like approve). `Event::Retry` returns the job to the `verifying` or `ci-and-review` stage of the pull request it failed on, with a factory turn, and resets the failed-round count and the checks-error count, so the factory runs the checks or watches the pull request again and the agent gets 5 fresh rounds. A job whose checks could not run 5 times in a row ends in `failed` with the `verifying` retry target, and Retry reruns the project's current checks command with 5 fresh attempts. The failure card for this job also shows a sentence to revise the project's local checks command or retry, and a link to `/settings/projects/` in the same tab. The page decides this from `Job::checks_could_not_run`, not from the reason text, so any other failure keeps the plain card. A job whose agent run failed, such as one stopped by the plan's 5-hour usage limit, keeps the stage and task of that run as its retry target, and `Event::Retry` runs the same task again in the same stage. The stage picks the session, so the run resumes the session that failed, in the same checkout, and keeps the failed-round count, because a failed agent run is not a failed round. When the run died mid-rebase, the checkout aborts the unfinished rebase before the next run, so the agent can start it again. A `Stage::Failed` keeps the retry target, so the core decides where a retry resumes. `Job::can_retry` reports whether a retry would resume the job, and the button and the endpoint both read it. A job stored before the target existed, such as jobs/10, carries none. The factory recognises it by its exact old reason, or for an agent failure by a reason that starts with "the agent run ended with", such as jobs/17 and jobs/20, and resumes at `ci-and-review` of its highest-numbered pull request. Watching that pull request finds the work left, or finds it merged and moves on to the next pull request. A legacy job with no pull request number is not retryable. A job closed unmerged, and a cancelled or merged job, reject `Retry`. Retry works on a dismissed failed job the same as on any failed job, see Job dismiss: it moves the job out of `Failed` and so clears the dismissal, and a later failure shows in the Failed section again. A stopped review retries too: a job in `ci-and-review` at `ReviewStopped` with a pull request number shows the Retry button, and where it resumes depends on why the review stopped, recorded on the ask as `ReviewStop`. A reviewer run that failed reruns the reviewer in its session; a review that hit the cap of 5 sends the last feedback to the implement session with 5 fresh rounds. A job stored in `ReviewStopped` before the field existed, such as jobs/28, retries as a reviewer failure. A stopped Renovate job retries too: `Event::Retry` at `Ask::Renovate` with the stopped state resets both rerun counts and reruns the failed CI runs, see Renovate pull request jobs. A ready or unsafe Renovate job has no Retry. A Renovate job whose agent run failed retries as any other failed agent run. The retry does not touch `created_at`, so the 30-day expiry still counts from the request. | @@ -449,8 +449,17 @@ No OpenRouter key was available, so each CLI ran with the settings above against - `openrouter_request` checks the model, then resolves the key, then picks the CLI, and applies `AgentFailed` on a failure before any checkout, as `local_request` does. The Renovate agent reuses it. - The key check runs in the executor before the worker starts: 401 or 403 and an unreachable host each fail the run and keep Retry. -- The session records its CLI in `sessions.local_cli` on the worker's first line, and a resumed session keeps it. `SHOWN_COST` shows a zero total as `$0.00` only for a session on Local, so a started OpenRouter session leaves a subscription job's zero total as a dash. The change that records the OpenRouter cost extends the rule. -- The run adds no cost row. It logs "OpenRouter run finished." with the token counts the CLI reported. A later change reads the cost from OpenRouter. +- The session records its CLI in `sessions.local_cli` on the worker's first line, and a resumed session keeps it. `SHOWN_COST` shows a zero total as `$0.00` for a job with a session on Local or OpenRouter, so a fetched cost of $0 reads `$0.00`. A zero total of any other job stays a dash. + +### Recording the cost OpenRouter charged + +`Scheduler::record_run_cost` hands an OpenRouter run to `record_openrouter_cost`, which spawns a tokio task outside the worker slots, so the lookup never fails the run or delays its next step. + +- The task asks `OpenRouterApi::generation` for each id in `RunReport.generation_ids`, with the run's own key. A 404 or an answer with no `data.total_cost` means OpenRouter has no cost yet. `OpenRouterCosts` asks again for the ids still unread after 2, 4, 8, 16 and 30 seconds, about a minute in all. A 401 or 403 stops at once. +- When every id reads, the sum goes through `Store::add_cost` and the log reads "OpenRouter run finished, $x.xx charged by OpenRouter." with the token counts when the CLI reported them. +- When an id stays unread, the output showed none, or the run had no key, the run adds no cost and the log reads "OpenRouter run finished. The cost could not be read from OpenRouter and is not counted." with the token counts. +- The run's own ids are the only ones counted, so a resumed session does not count earlier runs again. The dollar figure Claude Code reports and the Codex price table are ignored, and `add_session_cost` is never called. +- Claude Code shows an id as the `message.id` of each assistant message. Codex's stdout holds none and no read of its rollout file exists, so a Codex run on OpenRouter adds no cost and logs that it could not be read. Copilot's `assistant.message` line carries one in `data.apiCallId`, as the stub run above shows. Only a run against OpenRouter itself shows whether the real ids read back, which criterion 21 covers. Criterion 21, one run per CLI against OpenRouter with a real key, is not met by this pull request. From a52bf3965ea8c16ed29fbf0c61d22033031796e9 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:20:30 +0000 Subject: [PATCH 2/7] factory-server: fix OpenRouter cost review findings A zero from a subscription run stays a dash unless OpenRouter confirmed it, which the job_costs row now records in `fetched`. A late lookup files its charge under the stage and pull request of the run, and the timeline no longer reads that entry as a step change. A terminal job keeps polling while a lookup is pending. The lookup has a 90 second wall-clock deadline and records nothing when it expires. Comments that repeated the code are removed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/examples/e2e_fixture.rs | 16 ++- crates/factory-server/src/main.rs | 3 + crates/factory-server/src/openrouter.rs | 38 ++++-- crates/factory-server/src/pages.rs | 18 ++- crates/factory-server/src/scheduler.rs | 41 +++--- crates/factory-server/src/store.rs | 123 ++++++++++++++++-- crates/factory-server/src/timeline.rs | 11 +- crates/factory-server/src/web.rs | 5 + crates/factory-server/tests/dashboard.rs | 69 +++++++++- crates/factory-server/tests/scheduler.rs | 72 +++++++++- docs/design.md | 8 +- e2e/tests/job.spec.ts | 11 ++ 12 files changed, 361 insertions(+), 54 deletions(-) diff --git a/crates/factory-server/examples/e2e_fixture.rs b/crates/factory-server/examples/e2e_fixture.rs index 1f5f11a..4365cae 100644 --- a/crates/factory-server/examples/e2e_fixture.rs +++ b/crates/factory-server/examples/e2e_fixture.rs @@ -405,7 +405,13 @@ fn cost(store: &Store, flags: &HashMap>) -> Result<()> { Ok(flags.get(name).ok_or(format!("--{name} is required"))?[0].as_str()) }; let job = one("job")?.parse()?; - store.add_cost(job, one("usd")?.parse()?, false)?; + let usd = one("usd")?.parse()?; + if flags.contains_key("fetched") { + let at = store.get(job)?.job; + store.add_fetched_cost(job, usd, &at)?; + } else { + store.add_cost(job, usd, false)?; + } if let Ok(cli) = one("local-cli") { let cli = Cli::from_id(cli).ok_or("unknown --local-cli")?; store.session_uuid(job, Session::Planning, Agent::Local)?; @@ -511,6 +517,14 @@ fn main() -> Result<()> { ), "apply" => apply(&store, &flags)?, "cost" => cost(&store, &flags)?, + "cost-lookup" => { + let job = one("job")?.parse()?; + match one("state")?.as_str() { + "begin" => store.begin_cost_lookup(job)?, + "end" => store.end_cost_lookup(job)?, + _ => return Err("--state is begin or end".into()), + } + } "log" => { let job = one("job")?.parse()?; let text = one("text")?; diff --git a/crates/factory-server/src/main.rs b/crates/factory-server/src/main.rs index 50a5daa..b5990ed 100644 --- a/crates/factory-server/src/main.rs +++ b/crates/factory-server/src/main.rs @@ -273,6 +273,9 @@ async fn main() -> Result<(), Box> { local_probe: Arc::new(HttpLocalServerProbe::new()), openrouter: Arc::clone(&openrouter_api), }; + if let Err(err) = store.clear_cost_lookups() { + tracing::error!("clearing cost lookups: {err}"); + } let scheduler = Scheduler::new( Arc::clone(&store), Arc::clone(&projects), diff --git a/crates/factory-server/src/openrouter.rs b/crates/factory-server/src/openrouter.rs index 6af017d..7e4bdde 100644 --- a/crates/factory-server/src/openrouter.rs +++ b/crates/factory-server/src/openrouter.rs @@ -100,30 +100,52 @@ pub trait OpenRouterApi: Send + Sync { pub struct OpenRouterCosts { api: Arc, delays: Vec, + deadline: Duration, } impl OpenRouterCosts { - /// Asks again after 2, 4, 8, 16 and 30 seconds, so a generation that - /// `OpenRouter` has not stored yet is waited for about a minute. + /// Asks again after 2, 4, 8, 16 and 30 seconds, and gives up after 90 + /// seconds in all, requests included. #[must_use] pub fn new(api: Arc) -> Self { - Self::with_delays(api, [2, 4, 8, 16, 30].map(Duration::from_secs).to_vec()) + Self::with_limits( + api, + [2, 4, 8, 16, 30].map(Duration::from_secs).to_vec(), + Duration::from_secs(90), + ) } - /// As [`Self::new`], with the waits between the rounds of asking given. + /// As [`Self::new`], with the waits between the rounds of asking and the + /// time the whole lookup may take given. #[must_use] - pub fn with_delays(api: Arc, delays: Vec) -> Self { - OpenRouterCosts { api, delays } + pub fn with_limits( + api: Arc, + delays: Vec, + deadline: Duration, + ) -> Self { + OpenRouterCosts { + api, + delays, + deadline, + } } /// The sum of the costs of the generations `ids`, read with `key`. Each /// round asks only for the ids still unread. `None` when an id stays - /// unread after the last round, `OpenRouter` refuses the key, or `ids` is - /// empty. + /// unread after the last round or the deadline, `OpenRouter` refuses the + /// key, or `ids` is empty. A lookup that runs out of time returns no + /// partial sum. pub async fn total(&self, key: &str, ids: &[String]) -> Option { if ids.is_empty() { return None; } + tokio::time::timeout(self.deadline, self.read(key, ids)) + .await + .ok() + .flatten() + } + + async fn read(&self, key: &str, ids: &[String]) -> Option { let mut costs: Vec> = vec![None; ids.len()]; for round in 0..=self.delays.len() { for (id, slot) in ids.iter().zip(&mut costs) { diff --git a/crates/factory-server/src/pages.rs b/crates/factory-server/src/pages.rs index 60cd91d..b3e1c5d 100644 --- a/crates/factory-server/src/pages.rs +++ b/crates/factory-server/src/pages.rs @@ -4704,6 +4704,7 @@ pub fn job( auto_merge: bool, links: &JobLinks, prerequisites: &[PrerequisiteView], + cost_pending: bool, ) -> Markup { let job = &row.job; let repo_url = Links::of(project); @@ -4714,7 +4715,7 @@ pub fn job( &format!("Job #{id}"), &html! {}, &html! { - (job_poll(false, id, job)) + (job_poll(false, id, job, cost_pending)) (job_header(id, row, label, links, repo_url, cost_usd, estimated)) @if let Some(problem) = project.and_then(|project| project.forge.problem()) { div.card.failed { (problem) } @@ -4771,11 +4772,12 @@ pub fn job_fragment( auto_merge: bool, links: &JobLinks, prerequisites: &[PrerequisiteView], + cost_pending: bool, ) -> Markup { let job = &row.job; let repo_url = Links::of(project); html! { - @if terminal(job) { (job_poll(true, row.id, job)) } + @if terminal(job) { (job_poll(true, row.id, job, cost_pending)) } (cost_badge(true, cost_usd, any_estimated(events))) (timeline_region(true, job, events, models, efforts)) (status_region(true, row.id, label, job, settings, auto_merge, links, prerequisites)) @@ -4789,7 +4791,8 @@ pub fn job_fragment( } /// Merged, failed and cancelled jobs do not change again, so their page and -/// its fragments carry no polling attribute. +/// its fragments carry no polling attribute, unless an `OpenRouter` cost lookup +/// is still running and will add a cost and a log line. fn terminal(job: &Job) -> bool { matches!( job.stage(), @@ -4800,10 +4803,11 @@ fn terminal(job: &Job) -> bool { /// The hidden element that polls the job fragment. A running job polls every /// `POLL_TRIGGER` and lets htmx apply the out-of-band swaps the response /// carries; `hx-swap="none"` keeps it from swapping the response into itself. -/// A terminal job gets a bare element with no polling attribute, so the loop -/// stops both on first load and when a running page reaches a terminal stage. -fn job_poll(oob: bool, id: i64, job: &Job) -> Markup { - let polling = !terminal(job); +/// A terminal job with no lookup running gets a bare element with no polling +/// attribute, so the loop stops both on first load and when a running page +/// reaches a terminal stage. +fn job_poll(oob: bool, id: i64, job: &Job, cost_pending: bool) -> Markup { + let polling = !terminal(job) || cost_pending; html! { div #job-poll hx-swap-oob=[oob.then_some("true")] hx-get=[polling.then(|| format!("/jobs/{id}/fragment"))] diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 889c2a9..77c27a4 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -924,8 +924,6 @@ fn rerun_request( } } -/// The key an `OpenRouter` run pays with, kept before the request moves into -/// the run so the cost lookup afterwards can use it. fn openrouter_key_of(request: &AgentRequest) -> Option { request .provider @@ -2515,6 +2513,13 @@ impl Scheduler { usage.input_tokens, usage.output_tokens ) }); + // The job as the run leaves it, before the run's result moves it on. + let Ok(at) = self.store.get(job_id).map(|row| row.job) else { + return; + }; + if let Err(err) = self.store.begin_cost_lookup(job_id) { + tracing::error!("job {job_id}: {err}"); + } let store = Arc::clone(&self.store); let costs = Arc::clone(&self.costs); let ids = report.generation_ids.clone(); @@ -2523,20 +2528,23 @@ impl Scheduler { Some(key) => costs.total(key, &ids).await, None => None, }; - let mut text = match total { - Some(total) => match store.add_cost(job_id, total, false) { - Ok(()) => format!( - "OpenRouter run finished, {} charged by OpenRouter", - format_cost(total) - ), - Err(err) => { - tracing::error!("job {job_id}: {err}"); - return; - } - }, - None => "OpenRouter run finished. The cost could not be read from \ - OpenRouter and is not counted" + let recorded = total.map_or(Ok(None), |total| { + store + .add_fetched_cost(job_id, total, &at) + .map(|()| Some(total)) + }); + let mut text = match recorded { + Ok(Some(total)) => format!( + "OpenRouter run finished, {} charged by OpenRouter", + format_cost(total) + ), + Ok(None) => "OpenRouter run finished. The cost could not be read from \ + OpenRouter and is not counted" .to_owned(), + Err(err) => { + tracing::error!("job {job_id}: {err}"); + "OpenRouter run finished. The cost could not be recorded".to_owned() + } }; if let Some(tokens) = tokens { let _ = write!(text, ". {tokens}"); @@ -2545,6 +2553,9 @@ impl Scheduler { if let Err(err) = store.append_factory_log(job_id, &text) { tracing::error!("job {job_id}: {err}"); } + if let Err(err) = store.end_cost_lookup(job_id) { + tracing::error!("job {job_id}: {err}"); + } }); } diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index dd553da..9451473 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -139,7 +139,12 @@ CREATE TABLE IF NOT EXISTS job_files ( ); CREATE TABLE IF NOT EXISTS job_costs ( job_id INTEGER PRIMARY KEY REFERENCES jobs (id), - usd REAL NOT NULL + usd REAL NOT NULL, + fetched INTEGER NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS cost_lookups ( + job_id INTEGER PRIMARY KEY REFERENCES jobs (id), + pending INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS project_totals ( project TEXT PRIMARY KEY, @@ -611,12 +616,13 @@ pub struct ProjectTotals { pub jobs_merged: i64, } -/// Selects the `job_costs` rows to show as a cost: a positive total, or a zero -/// total of a job that ran a worker on Local or `OpenRouter`, whose cost is -/// known to be nothing, such as a `:free` model. Another zero row reads as no cost. -const SHOWN_COST: &str = "(c.usd > 0 OR EXISTS ( +/// Selects the `job_costs` rows to show as a cost: a positive total, a zero +/// total `OpenRouter` charged and the factory read back, such as a `:free` +/// model, or a zero total of a job that ran a worker on Local. Another zero row +/// reads as no cost. +const SHOWN_COST: &str = "(c.usd > 0 OR c.fetched = 1 OR EXISTS ( SELECT 1 FROM sessions s - WHERE s.job_id = c.job_id AND s.agent IN ('local', 'openrouter') AND s.local_cli IS NOT NULL))"; + WHERE s.job_id = c.job_id AND s.agent = 'local' AND s.local_cli IS NOT NULL))"; /// One model's Codex prices, in USD per million tokens. The factory estimates a /// Codex run's cost from the row for the model it ran, since Codex reports token @@ -1084,6 +1090,7 @@ impl Store { [], )?; } + Self::migrate_job_costs_fetched(&conn)?; conn.execute("INSERT INTO store_boots DEFAULT VALUES", [])?; let epoch = u64::try_from(conn.last_insert_rowid()).unwrap_or(0); Ok(Store { @@ -1129,6 +1136,21 @@ impl Store { /// its own. SQLite cannot change a constraint in place, so a table without /// the column is rebuilt with every row on `github`. A fresh database /// already has the column from SCHEMA, so this skips it. + fn migrate_job_costs_fetched(conn: &Connection) -> Result<(), StoreError> { + let has_fetched: i64 = conn.query_row( + "SELECT COUNT(*) FROM pragma_table_info('job_costs') WHERE name = 'fetched'", + [], + |row| row.get(0), + )?; + if has_fetched == 0 { + conn.execute( + "ALTER TABLE job_costs ADD COLUMN fetched INTEGER NOT NULL DEFAULT 0", + [], + )?; + } + Ok(()) + } + fn migrate_project_forge(conn: &Connection) -> Result<(), StoreError> { let has_forge: i64 = conn.query_row( "SELECT COUNT(*) FROM pragma_table_info('projects') WHERE name = 'forge'", @@ -1954,6 +1976,7 @@ impl Store { "job_images", "job_files", "job_costs", + "cost_lookups", "job_events", "pr_watermarks", "logs", @@ -2528,10 +2551,83 @@ impl Store { pub fn add_cost(&self, id: i64, usd: f64, estimated: bool) -> Result<(), StoreError> { let mut conn = self.conn(); let tx = conn.transaction()?; - Self::add_cost_in(&tx, id, usd, estimated)?; + Self::add_cost_in(&tx, id, usd, estimated, None)?; + Ok(tx.commit()?) + } + + /// Adds `usd`, the cost `OpenRouter` charged for a run, to job `id`. The + /// `cost` entry is filed under the stage and turn of `at`, the job as the + /// run left it, because the job may have moved on by the time `OpenRouter` + /// answers. A zero shows as `$0.00`, since `OpenRouter` confirmed it. + /// + /// # Errors + /// + /// Fails with [`StoreError::NotFound`] when there is no job `id`, and on + /// a database error. + pub fn add_fetched_cost(&self, id: i64, usd: f64, at: &Job) -> Result<(), StoreError> { + let mut conn = self.conn(); + let tx = conn.transaction()?; + Self::add_cost_in(&tx, id, usd, false, Some(at))?; + tx.execute("UPDATE job_costs SET fetched = 1 WHERE job_id = ?1", [id])?; Ok(tx.commit()?) } + /// Marks that a cost lookup for job `id` is running, so an open job page + /// keeps polling after the job ends. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn begin_cost_lookup(&self, id: i64) -> Result<(), StoreError> { + self.conn().execute( + "INSERT INTO cost_lookups (job_id, pending) VALUES (?1, 1) + ON CONFLICT (job_id) DO UPDATE SET pending = pending + 1", + [id], + )?; + Ok(()) + } + + /// Marks that a lookup begun with [`Self::begin_cost_lookup`] is over. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn end_cost_lookup(&self, id: i64) -> Result<(), StoreError> { + let conn = self.conn(); + conn.execute( + "UPDATE cost_lookups SET pending = pending - 1 WHERE job_id = ?1", + [id], + )?; + conn.execute("DELETE FROM cost_lookups WHERE pending <= 0", [])?; + Ok(()) + } + + /// Whether a cost lookup for job `id` is running. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn cost_lookup_pending(&self, id: i64) -> Result { + Ok(self + .conn() + .query_row("SELECT 1 FROM cost_lookups WHERE job_id = ?1", [id], |_| { + Ok(()) + }) + .optional()? + .is_some()) + } + + /// Forgets every running lookup. The factory calls it at start, when no + /// lookup of an earlier process can still run. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn clear_cost_lookups(&self) -> Result<(), StoreError> { + self.conn().execute("DELETE FROM cost_lookups", [])?; + Ok(()) + } + /// Adds the cost of one run to job `id` when the agent reports `total`, /// the cost of the whole session whose factory UUID is `uuid` so far. /// Claude reports that total, and it keeps counting across `--resume`, so @@ -2562,7 +2658,7 @@ impl Store { "UPDATE sessions SET cost_usd = ?2 WHERE uuid = ?1", params![uuid, total], )?; - Self::add_cost_in(&tx, id, usd, false)?; + Self::add_cost_in(&tx, id, usd, false, None)?; tx.commit()?; Ok(usd) } @@ -2572,6 +2668,7 @@ impl Store { id: i64, usd: f64, estimated: bool, + at: Option<&Job>, ) -> Result<(), StoreError> { let closed = tx .query_row( @@ -2585,7 +2682,15 @@ impl Store { return Ok(()); } let row = Self::load(tx, id)?; - Self::record_cost(tx, id, "cost", &row.job, None, Some(usd), estimated)?; + Self::record_cost( + tx, + id, + "cost", + at.unwrap_or(&row.job), + None, + Some(usd), + estimated, + )?; tx.execute( "INSERT INTO job_costs (job_id, usd) VALUES (?1, ?2) ON CONFLICT (job_id) DO UPDATE SET usd = usd + excluded.usd", diff --git a/crates/factory-server/src/timeline.rs b/crates/factory-server/src/timeline.rs index 66e2266..9c0def9 100644 --- a/crates/factory-server/src/timeline.rs +++ b/crates/factory-server/src/timeline.rs @@ -107,8 +107,14 @@ fn build(job: &Job, events: &[JobEvent]) -> Timeline { if let Some(step) = current.and_then(|i: usize| steps.get_mut(i)) { note(step, event); } - let at = event.at.as_str(); let entered = stage_order(&event.stage, event.pr, prs); + if event.event == "cost" { + if let (Some(usd), Some(step)) = (event.usd, entered.and_then(|i| steps.get_mut(i))) { + step.usd += usd; + } + continue; + } + let at = event.at.as_str(); if entered != active { if let Some(step) = active.and_then(|i| steps.get_mut(i)) { step.seconds += elapsed(step.visit.as_deref(), at); @@ -122,9 +128,6 @@ fn build(job: &Job, events: &[JobEvent]) -> Timeline { if entered.is_some() { current = entered; } - if let (Some(usd), Some(step)) = (event.usd, current.and_then(|i| steps.get_mut(i))) { - step.usd += usd; - } } if !matches!(job.stage(), Stage::Failed { .. } | Stage::Cancelled) { current = stage_order(job.stage().name(), job.stage().pr(), prs); diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 8c6abca..4c2c13a 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -1334,6 +1334,7 @@ struct JobData { logs: Vec, events: Vec, cost_usd: Option, + cost_pending: bool, models: StageModels, efforts: StageEfforts, auto_merge: bool, @@ -1390,6 +1391,7 @@ fn load_job(state: &AppState, login: &str, id: i64) -> Result let logs = state.store.logs(id, LOG_LINES)?; let events = state.store.events(id)?; let cost_usd = state.store.recorded_cost(id)?; + let cost_pending = state.store.cost_lookup_pending(id)?; let defaults = project .as_ref() .map(|project| project.models.clone()) @@ -1410,6 +1412,7 @@ fn load_job(state: &AppState, login: &str, id: i64) -> Result logs, events, cost_usd, + cost_pending, models, efforts, auto_merge, @@ -1498,6 +1501,7 @@ async fn show_job( data.auto_merge, &data.links, &data.prerequisites, + data.cost_pending, )) } @@ -1525,6 +1529,7 @@ async fn job_fragment( data.auto_merge, &data.links, &data.prerequisites, + data.cost_pending, )) } diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index 46cfea2..8ddd3ce 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -1706,7 +1706,11 @@ async fn an_openrouter_job_shows_what_openrouter_charged_with_no_estimate_mark() .store .record_session_provider_cli(id, Session::Planning, Cli::ClaudeCode) .unwrap(); - dashboard.store.add_cost(id, 0.10 + 0.25, false).unwrap(); + let at = dashboard.store.get(id).unwrap().job; + dashboard + .store + .add_fetched_cost(id, 0.10 + 0.25, &at) + .unwrap(); let page = dashboard.get(&format!("/jobs/{id}")).await; assert!( @@ -1717,7 +1721,7 @@ async fn an_openrouter_job_shows_what_openrouter_charged_with_no_estimate_mark() } #[tokio::test] -async fn an_openrouter_job_whose_generations_were_free_shows_zero_dollars() { +async fn a_started_openrouter_session_leaves_a_subscription_zero_cost_as_a_dash() { let dashboard = dashboard(); let id = dashboard.new_job().await; dashboard.store.add_cost(id, 0.0, false).unwrap(); @@ -1730,6 +1734,67 @@ async fn an_openrouter_job_whose_generations_were_free_shows_zero_dollars() { .record_session_provider_cli(id, Session::Planning, Cli::Codex) .unwrap(); + let page = dashboard.get(&format!("/jobs/{id}")).await; + assert!( + page.body + .contains("–") + ); +} + +#[tokio::test] +async fn a_late_openrouter_cost_stays_on_its_step_and_does_not_move_the_job_back() { + let dashboard = dashboard(); + let id = dashboard.new_job().await; + dashboard.apply(id, Event::Start); + let at = dashboard.store.get(id).unwrap().job; + dashboard.apply(id, Event::Agent(AgentResult::Clarified)); + dashboard.store.add_fetched_cost(id, 0.4, &at).unwrap(); + + let page = dashboard.get(&format!("/jobs/{id}")).await; + let clarifying = timeline_step(&page.body, "clarifying"); + assert!(clarifying.contains("$0.40")); + assert!(!clarifying.contains("class=\"current\"")); + assert!(timeline_step(&page.body, "spec").contains("class=\"current\"")); +} + +#[tokio::test] +async fn a_finished_job_keeps_polling_while_a_cost_lookup_is_pending() { + let dashboard = dashboard(); + let id = dashboard.new_job().await; + dashboard.apply(id, Event::Cancel); + let path = format!("/jobs/{id}"); + assert!(!dashboard.get(&path).await.body.contains("hx-trigger")); + + dashboard.store.begin_cost_lookup(id).unwrap(); + let page = dashboard.get(&path).await; + assert!( + page.body + .contains(&format!("hx-get=\"/jobs/{id}/fragment\"")) + ); + let fragment = dashboard.get(&format!("{path}/fragment")).await; + assert!(fragment.body.contains("id=\"job-poll\"")); + assert!(fragment.body.contains("hx-trigger")); + + dashboard.store.end_cost_lookup(id).unwrap(); + let fragment = dashboard.get(&format!("{path}/fragment")).await; + assert!(!fragment.body.contains("hx-trigger")); +} + +#[tokio::test] +async fn an_openrouter_job_whose_generations_were_free_shows_zero_dollars() { + let dashboard = dashboard(); + let id = dashboard.new_job().await; + let at = dashboard.store.get(id).unwrap().job; + dashboard.store.add_fetched_cost(id, 0.0, &at).unwrap(); + dashboard + .store + .session_uuid(id, Session::Planning, Agent::OpenRouter) + .unwrap(); + dashboard + .store + .record_session_provider_cli(id, Session::Planning, Cli::Codex) + .unwrap(); + let page = dashboard.get(&format!("/jobs/{id}")).await; assert!( page.body diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index 0a7b5a5..a567ec0 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -34,6 +34,10 @@ use tokio::sync::{Notify, Semaphore}; struct FakeGenerations { costs: Mutex>, keys: Mutex>, + /// Lookups wait for a permit while this is set. + gate: Mutex>>, + /// An id whose lookup never answers. + hangs: Mutex>, } impl OpenRouterApi for FakeGenerations { @@ -48,6 +52,13 @@ impl OpenRouterApi for FakeGenerations { fn generation<'a>(&'a self, id: &'a str, key: &'a str) -> OpenRouterGenerationFuture<'a> { Box::pin(async move { self.keys.lock().unwrap().push(key.to_owned()); + let gate = self.gate.lock().unwrap().clone(); + if let Some(gate) = gate { + gate.acquire().await.unwrap().forget(); + } + if self.hangs.lock().unwrap().as_deref() == Some(id) { + std::future::pending::<()>().await; + } self.costs .lock() .unwrap() @@ -59,27 +70,24 @@ impl OpenRouterApi for FakeGenerations { } } -/// Lookups that answer from `table` and ask again after a millisecond. fn fake_costs(table: &[(&str, f64)]) -> (OpenRouterCosts, Arc) { let api = Arc::new(FakeGenerations::default()); *api.costs.lock().unwrap() = table .iter() .map(|(id, cost)| ((*id).to_owned(), *cost)) .collect(); - let costs = OpenRouterCosts::with_delays( + let costs = OpenRouterCosts::with_limits( Arc::clone(&api) as Arc, vec![Duration::from_millis(1); 3], + Duration::from_secs(30), ); (costs, api) } -/// Lookups that find nothing. fn no_costs() -> OpenRouterCosts { fake_costs(&[]).0 } -/// Waits for the background cost lookup of an `OpenRouter` run to log its -/// outcome, and returns that line. async fn openrouter_finished(store: &Store, id: i64, count: usize) -> Vec { for _ in 0..500 { let lines = finished_lines_with(store, id, "OpenRouter run finished"); @@ -283,7 +291,6 @@ impl FakeExecutor { self.sessions.lock().unwrap().push_back(id.to_owned()); } - /// Makes the next run's output show the generation ids `ids`. fn report_generations(&self, ids: &[&str]) { self.generations .lock() @@ -10446,3 +10453,56 @@ async fn an_openrouter_generation_that_cost_nothing_records_a_zero_row() { ); assert_eq!(store.recorded_cost(id).unwrap(), Some(0.0)); } + +#[tokio::test] +async fn a_lookup_that_ends_after_the_job_moved_on_files_its_cost_under_the_run_step() { + let (costs, api) = fake_costs(&[("gen-1", 0.4)]); + let gate = Arc::new(Semaphore::new(0)); + *api.gate.lock().unwrap() = Some(Arc::clone(&gate)); + let (store, executor, scheduler, secrets) = + setup_openrouter_with(|_| Event::Agent(AgentResult::Clarified), costs); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.report_generations(&["gen-1"]); + executor.release(1); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + step(&scheduler).await; + + assert_ne!(store.get(id).unwrap().job.stage(), &Stage::Clarifying); + assert!(store.cost_lookup_pending(id).unwrap()); + gate.add_permits(10); + openrouter_finished(&store, id, 1).await; + + assert!(!store.cost_lookup_pending(id).unwrap()); + let cost = store + .events(id) + .unwrap() + .into_iter() + .find(|event| event.event == "cost") + .expect("the cost entry"); + assert_eq!(cost.stage, "clarifying"); + assert_eq!(cost.usd, Some(0.4)); +} + +#[tokio::test] +async fn a_lookup_that_runs_out_of_time_records_no_partial_cost() { + let api = Arc::new(FakeGenerations::default()); + *api.costs.lock().unwrap() = vec![("gen-1".to_owned(), 0.1)]; + *api.hangs.lock().unwrap() = Some("gen-2".to_owned()); + let costs = OpenRouterCosts::with_limits( + Arc::clone(&api) as Arc, + vec![Duration::from_millis(1); 3], + Duration::from_millis(100), + ); + let (store, executor, scheduler, secrets) = setup_openrouter_with(|_| questions(), costs); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.report_generations(&["gen-1", "gen-2"]); + executor.release(1); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + step(&scheduler).await; + + let lines = openrouter_finished(&store, id, 1).await; + assert!(lines[0].contains("could not be read from OpenRouter")); + assert_eq!(store.recorded_cost(id).unwrap(), None); + assert_eq!(store.project_totals("maestro").unwrap().usd, 0.0); + assert!(!store.cost_lookup_pending(id).unwrap()); +} diff --git a/docs/design.md b/docs/design.md index 30be2aa..ab3969f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -455,12 +455,16 @@ No OpenRouter key was available, so each CLI ran with the settings above against `Scheduler::record_run_cost` hands an OpenRouter run to `record_openrouter_cost`, which spawns a tokio task outside the worker slots, so the lookup never fails the run or delays its next step. -- The task asks `OpenRouterApi::generation` for each id in `RunReport.generation_ids`, with the run's own key. A 404 or an answer with no `data.total_cost` means OpenRouter has no cost yet. `OpenRouterCosts` asks again for the ids still unread after 2, 4, 8, 16 and 30 seconds, about a minute in all. A 401 or 403 stops at once. -- When every id reads, the sum goes through `Store::add_cost` and the log reads "OpenRouter run finished, $x.xx charged by OpenRouter." with the token counts when the CLI reported them. +- The task asks `OpenRouterApi::generation` for each id in `RunReport.generation_ids`, with the run's own key. A 404 or an answer with no `data.total_cost` means OpenRouter has no cost yet. `OpenRouterCosts` asks again for the ids still unread after 2, 4, 8, 16 and 30 seconds, about a minute in all. A 401 or 403 stops at once. A wall-clock deadline of 90 seconds covers the whole lookup, including each request's own 10-second timeout, so a slow endpoint cannot keep the task alive longer. When the deadline expires the lookup returns nothing and no partial sum is recorded. +- When every id reads, the sum goes through `Store::add_fetched_cost`, which sets the `fetched` flag on the job's `job_costs` row, and the log reads "OpenRouter run finished, $x.xx charged by OpenRouter." with the token counts when the CLI reported them. - When an id stays unread, the output showed none, or the run had no key, the run adds no cost and the log reads "OpenRouter run finished. The cost could not be read from OpenRouter and is not counted." with the token counts. - The run's own ids are the only ones counted, so a resumed session does not count earlier runs again. The dollar figure Claude Code reports and the Codex price table are ignored, and `add_session_cost` is never called. - Claude Code shows an id as the `message.id` of each assistant message. Codex's stdout holds none and no read of its rollout file exists, so a Codex run on OpenRouter adds no cost and logs that it could not be read. Copilot's `assistant.message` line carries one in `data.apiCallId`, as the stub run above shows. Only a run against OpenRouter itself shows whether the real ids read back, which criterion 21 covers. +- The task takes a snapshot of the job before the run's result is applied. `add_fetched_cost` files the `cost` event under that snapshot's stage and pull request index, so a lookup that ends after the job moved on charges the step that ran. `timeline::build` adds a `cost` event's amount to the step of its own stage and never treats it as a transition, so the current step stays as it is. +- A zero shows as `$0.00` only when `fetched` is set, that is, OpenRouter confirmed a free run, or when a Local session has a CLI. A plain zero from a subscription run in the same job stays a dash, even when an OpenRouter session started and its lookup failed. +- `begin_cost_lookup` writes the job to the `cost_lookups` table before the task spawns and `end_cost_lookup` removes it when the task ends. The job page polls its fragment while the job is live or has a row there, so a failed or merged job still shows a late charge and log line without a reload. The table lives in SQLite because the browser tests change state from a second process. `main` clears it before the scheduler starts, since a restart ends every task. + Criterion 21, one run per CLI against OpenRouter with a real key, is not met by this pull request. ## Layout diff --git a/e2e/tests/job.spec.ts b/e2e/tests/job.spec.ts index 4b514d1..968febe 100644 --- a/e2e/tests/job.spec.ts +++ b/e2e/tests/job.spec.ts @@ -1040,3 +1040,14 @@ test('a recorded Local run shows $0.00 and a subscription run with no cost shows await expect(cost(local)).toHaveText('$0.00'); await expect(cost(subscription)).toHaveText('–'); }); + +test('a finished job keeps polling until its pending OpenRouter cost arrives', async ({ page, factory, project }) => { + const id = newJob(factory, project, 'failed'); + factory.fixture('cost-lookup', '--job', id, '--state', 'begin'); + await page.goto(`/jobs/${id}`); + await expect(page.locator('#job-cost')).toHaveText('–'); + + factory.fixture('cost', '--job', id, '--usd', '0.42', '--fetched', 'true'); + factory.fixture('cost-lookup', '--job', id, '--state', 'end'); + await expect(page.locator('#job-cost')).toHaveText('$0.42'); +}); From 69dc2074a2c1748d321a7e050fe8f0a4cab3fd18 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:33:39 +0000 Subject: [PATCH 3/7] factory-server: read the run step and pending lookup earlier The job page reads the pending lookup before the log and the cost, so a lookup that ends mid-read keeps the page polling. A run's charge is filed under the job as it was when the run was dispatched, so a cancellation before the report cannot move it off the step. The design and the Local-only rule in the store now say a confirmed OpenRouter zero shows as $0.00, and the project forge migration comment is back above its function. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/scheduler.rs | 49 ++++++++++++++++-------- crates/factory-server/src/store.rs | 13 ++++--- crates/factory-server/src/web.rs | 4 +- crates/factory-server/tests/scheduler.rs | 29 ++++++++++++++ docs/design.md | 2 +- e2e/tests/job.spec.ts | 17 ++++++++ 6 files changed, 89 insertions(+), 25 deletions(-) diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 77c27a4..04d2240 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -2386,26 +2386,20 @@ impl Scheduler { let session_uuid = request.session_id.clone(); let cost_session = request.session_id.clone(); let session: SessionSink = Box::new(move |id| { - if let Err(err) = session_store.set_agent_session(&session_uuid, &id) { - tracing::error!("job {job_id}: {err}"); - } + session_store + .set_agent_session(&session_uuid, &id) + .unwrap_or_else(|err| tracing::error!("job {job_id}: {err}")); }); // The model the run passed, kept before the request moves into the run, // so a Codex run can look up its price by it afterwards. let (model, agent) = (request.model.clone(), request.agent); let openrouter_key = openrouter_key_of(&request); + let dispatched = self.store.get(job_id).ok().map(|row| row.job); let report = self .executor .run_agent(settings, request, sink, session) .await; - // Each active server the agent read as not connected in the run's init - // line gets its warning, deduped against a proxy warning for the same - // server already recorded during the run. - for unavailable in &report.mcp_unavailable { - self.mcp - .warnings - .record(job_id, &unavailable.server, &unavailable.reason); - } + self.record_unavailable_servers(job_id, &report); self.record_run_cost( job_id, &cost_session, @@ -2413,6 +2407,7 @@ impl Scheduler { model.as_deref(), &report, openrouter_key, + dispatched, ); match report.head { Some(head) if matches!(report.event, Event::QuickReviewed { .. }) => { @@ -2502,21 +2497,34 @@ impl Scheduler { } } + /// Each active server the agent read as not connected in the run's init + /// line gets its warning, deduped against a proxy warning for the same + /// server already recorded during the run. + fn record_unavailable_servers(&self, job_id: i64, report: &RunReport) { + for unavailable in &report.mcp_unavailable { + self.mcp + .warnings + .record(job_id, &unavailable.server, &unavailable.reason); + } + } + /// Reads what `OpenRouter` charged for the generations `report` shows with /// `key`, in the background so the run's next step never waits for it, and /// records the sum. When the cost cannot be read, the run adds no cost and /// the log says so. - fn record_openrouter_cost(&self, job_id: i64, report: &RunReport, key: Option) { + fn record_openrouter_cost( + &self, + job_id: i64, + report: &RunReport, + key: Option, + at: Job, + ) { let tokens = report.token_usage.map(|usage| { format!( "{} input tokens, {} output tokens", usage.input_tokens, usage.output_tokens ) }); - // The job as the run leaves it, before the run's result moves it on. - let Ok(at) = self.store.get(job_id).map(|row| row.job) else { - return; - }; if let Err(err) = self.store.begin_cost_lookup(job_id) { tracing::error!("job {job_id}: {err}"); } @@ -2571,6 +2579,10 @@ impl Scheduler { /// no cost at all. An `OpenRouter` run records what `OpenRouter` charged for /// the generations its output showed, read with `openrouter_key` in the /// background, so the run's next step never waits for it. + #[allow( + clippy::too_many_arguments, + reason = "the run's report, key and dispatch snapshot are each needed" + )] fn record_run_cost( &self, job_id: i64, @@ -2579,6 +2591,7 @@ impl Scheduler { model: Option<&str>, report: &RunReport, openrouter_key: Option, + dispatched: Option, ) { if agent == Agent::Local { // A local model has no price. The run adds a row of zero, so the job @@ -2600,7 +2613,9 @@ impl Scheduler { return; } if agent == Agent::OpenRouter { - self.record_openrouter_cost(job_id, report, openrouter_key); + if let Some(at) = dispatched { + self.record_openrouter_cost(job_id, report, openrouter_key, at); + } return; } if agent == Agent::Copilot { diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index 9451473..2665be0 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -1132,10 +1132,6 @@ impl Store { Ok(()) } - /// `forge` joined `projects` after the table shipped with `repo` unique on - /// its own. SQLite cannot change a constraint in place, so a table without - /// the column is rebuilt with every row on `github`. A fresh database - /// already has the column from SCHEMA, so this skips it. fn migrate_job_costs_fetched(conn: &Connection) -> Result<(), StoreError> { let has_fetched: i64 = conn.query_row( "SELECT COUNT(*) FROM pragma_table_info('job_costs') WHERE name = 'fetched'", @@ -1151,6 +1147,10 @@ impl Store { Ok(()) } + /// `forge` joined `projects` after the table shipped with `repo` unique on + /// its own. SQLite cannot change a constraint in place, so a table without + /// the column is rebuilt with every row on `github`. A fresh database + /// already has the column from SCHEMA, so this skips it. fn migrate_project_forge(conn: &Connection) -> Result<(), StoreError> { let has_forge: i64 = conn.query_row( "SELECT COUNT(*) FROM pragma_table_info('projects') WHERE name = 'forge'", @@ -2926,8 +2926,9 @@ impl Store { } /// The API cost of job `id` in USD, or `None` when the job has no cost row. - /// A zero row counts only for a job that started a Local worker, so it - /// shows `$0.00`. Any other zero row reads as no cost. + /// A zero row counts only for a job that started a Local worker or + /// whose `OpenRouter` lookup confirmed it, so it shows `$0.00`. Any other zero + /// row reads as no cost. /// /// # Errors /// diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 4c2c13a..60fd96d 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -1385,13 +1385,15 @@ fn keep_session_settings( } fn load_job(state: &AppState, login: &str, id: i64) -> Result { + // Read before the log and the cost, so a lookup that ends later has + // already written them when this reads no pending lookup. + let cost_pending = state.store.cost_lookup_pending(id)?; let row = state.store.get(id)?; let project = state.projects.lookup(&row.project)?; let settings = state.store.settings()?; let logs = state.store.logs(id, LOG_LINES)?; let events = state.store.events(id)?; let cost_usd = state.store.recorded_cost(id)?; - let cost_pending = state.store.cost_lookup_pending(id)?; let defaults = project .as_ref() .map(|project| project.models.clone()) diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index a567ec0..ea86687 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -10506,3 +10506,32 @@ async fn a_lookup_that_runs_out_of_time_records_no_partial_cost() { assert_eq!(store.project_totals("maestro").unwrap().usd, 0.0); assert!(!store.cost_lookup_pending(id).unwrap()); } + +#[tokio::test] +async fn a_charge_for_a_run_cancelled_before_its_report_stays_on_the_run_step() { + let (costs, _api) = fake_costs(&[("gen-1", 0.4)]); + let (store, executor, scheduler, secrets) = setup_openrouter_with(|_| questions(), costs); + secrets.set_openrouter_key("factory-key").unwrap(); + executor.report_generations(&["gen-1"]); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + scheduler.tick().await.unwrap(); + for _ in 0..200 { + if store.get(id).unwrap().job.stage() == &Stage::Clarifying { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + tokio::time::sleep(Duration::from_millis(100)).await; + store.apply(id, Event::Cancel).unwrap(); + executor.release(1); + openrouter_finished(&store, id, 1).await; + + let cost = store + .events(id) + .unwrap() + .into_iter() + .find(|event| event.event == "cost") + .expect("the cost entry"); + assert_eq!(cost.stage, "clarifying"); + assert_eq!(cost.usd, Some(0.4)); +} diff --git a/docs/design.md b/docs/design.md index ab3969f..f665f0b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -449,7 +449,7 @@ No OpenRouter key was available, so each CLI ran with the settings above against - `openrouter_request` checks the model, then resolves the key, then picks the CLI, and applies `AgentFailed` on a failure before any checkout, as `local_request` does. The Renovate agent reuses it. - The key check runs in the executor before the worker starts: 401 or 403 and an unreachable host each fail the run and keep Retry. -- The session records its CLI in `sessions.local_cli` on the worker's first line, and a resumed session keeps it. `SHOWN_COST` shows a zero total as `$0.00` for a job with a session on Local or OpenRouter, so a fetched cost of $0 reads `$0.00`. A zero total of any other job stays a dash. +- The session records its CLI in `sessions.local_cli` on the worker's first line, and a resumed session keeps it. `SHOWN_COST` shows a zero total as `$0.00` for a job with a Local session or a cost OpenRouter confirmed (`fetched`), so a fetched cost of $0 reads `$0.00`. Any other zero total stays a dash, even when an OpenRouter session started. ### Recording the cost OpenRouter charged diff --git a/e2e/tests/job.spec.ts b/e2e/tests/job.spec.ts index 968febe..b11f872 100644 --- a/e2e/tests/job.spec.ts +++ b/e2e/tests/job.spec.ts @@ -1051,3 +1051,20 @@ test('a finished job keeps polling until its pending OpenRouter cost arrives', a factory.fixture('cost-lookup', '--job', id, '--state', 'end'); await expect(page.locator('#job-cost')).toHaveText('$0.42'); }); + +test('a lookup that ends during a refresh leaves the next poll to show its charge', async ({ page, factory, project }) => { + const id = newJob(factory, project, 'failed'); + factory.fixture('cost-lookup', '--job', id, '--state', 'begin'); + let held = false; + await page.route(`**/jobs/${id}/fragment`, async (route) => { + const response = await route.fetch(); + if (!held) { + held = true; + factory.fixture('cost', '--job', id, '--usd', '0.42', '--fetched', 'true'); + factory.fixture('cost-lookup', '--job', id, '--state', 'end'); + } + await route.fulfill({ response }); + }); + await page.goto(`/jobs/${id}`); + await expect(page.locator('#job-cost')).toHaveText('$0.42'); +}); From cd91e4b05debf103ef818acb7ce147a1fdfae49a Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:45:15 +0000 Subject: [PATCH 4/7] factory-server: pass the dispatched job to the worker The worker receives the job that selected the task instead of reading it again, so a cancellation after dispatch cannot move a charge off its step, and a store error is no longer dropped. The job page reads the job row before the pending lookup, which closes the race where a lookup began and the job ended between the two reads. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/scheduler.rs | 18 +++++++++++------- crates/factory-server/src/web.rs | 6 +++--- crates/factory-server/tests/scheduler.rs | 7 ------- 3 files changed, 14 insertions(+), 17 deletions(-) diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 04d2240..0079ca0 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -1042,8 +1042,9 @@ impl Scheduler { }; let scheduler = Arc::clone(self); let settings = settings.clone(); + let job = job.clone(); self.spawn(row.id, Kind::Worker, async move { - scheduler.agent(&settings, request, skipped).await; + scheduler.agent(&settings, request, skipped, job).await; }); } Command::RunChecks { pr } => { @@ -2319,7 +2320,13 @@ impl Scheduler { Ok(()) } - async fn agent(&self, settings: &Settings, request: AgentRequest, skipped: Vec) { + async fn agent( + &self, + settings: &Settings, + request: AgentRequest, + skipped: Vec, + dispatched: Job, + ) { let job_id = request.job_id; // The run's proxy token is revoked when this guard drops: at the end of // the run, or when a cancel aborts and drops this future. @@ -2394,7 +2401,6 @@ impl Scheduler { // so a Codex run can look up its price by it afterwards. let (model, agent) = (request.model.clone(), request.agent); let openrouter_key = openrouter_key_of(&request); - let dispatched = self.store.get(job_id).ok().map(|row| row.job); let report = self .executor .run_agent(settings, request, sink, session) @@ -2591,7 +2597,7 @@ impl Scheduler { model: Option<&str>, report: &RunReport, openrouter_key: Option, - dispatched: Option, + dispatched: Job, ) { if agent == Agent::Local { // A local model has no price. The run adds a row of zero, so the job @@ -2613,9 +2619,7 @@ impl Scheduler { return; } if agent == Agent::OpenRouter { - if let Some(at) = dispatched { - self.record_openrouter_cost(job_id, report, openrouter_key, at); - } + self.record_openrouter_cost(job_id, report, openrouter_key, dispatched); return; } if agent == Agent::Copilot { diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 60fd96d..2ad8c59 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -1385,10 +1385,10 @@ fn keep_session_settings( } fn load_job(state: &AppState, login: &str, id: i64) -> Result { - // Read before the log and the cost, so a lookup that ends later has - // already written them when this reads no pending lookup. - let cost_pending = state.store.cost_lookup_pending(id)?; let row = state.store.get(id)?; + // Read after the job and before the log and the cost: a lookup begins + // before the job ends, and it writes both before it ends. + let cost_pending = state.store.cost_lookup_pending(id)?; let project = state.projects.lookup(&row.project)?; let settings = state.store.settings()?; let logs = state.store.logs(id, LOG_LINES)?; diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index ea86687..cd8d703 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -10515,13 +10515,6 @@ async fn a_charge_for_a_run_cancelled_before_its_report_stays_on_the_run_step() executor.report_generations(&["gen-1"]); let id = store.create("maestro", "alice", "Add a button").unwrap(); scheduler.tick().await.unwrap(); - for _ in 0..200 { - if store.get(id).unwrap().job.stage() == &Stage::Clarifying { - break; - } - tokio::time::sleep(Duration::from_millis(5)).await; - } - tokio::time::sleep(Duration::from_millis(100)).await; store.apply(id, Event::Cancel).unwrap(); executor.release(1); openrouter_finished(&store, id, 1).await; From 69a5044771566450a59a684203f5cf714549a1b8 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:57:11 +0000 Subject: [PATCH 5/7] factory-server: count an OpenRouter worker as a pending lookup A cancel can end the job before the worker reaches its cost lookup, so the page rendered by the cancel redirect had no poller and missed the late charge. The scheduler now counts the worker in cost_lookups from dispatch until it ends, and the lookup it starts counts on its own. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/scheduler.rs | 40 +++++++++++++++++++++++- crates/factory-server/tests/scheduler.rs | 1 + docs/design.md | 2 +- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 0079ca0..d033d24 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -847,6 +847,43 @@ impl Drop for TokenGuard { } } +/// Counts an `OpenRouter` worker as a pending cost lookup from its dispatch +/// until it ends or is aborted, so a job page that renders in between keeps +/// polling. The lookup the worker starts counts on its own, so the page never +/// sees a gap between the two. +struct WorkerCostGuard { + store: Arc, + job_id: i64, +} + +impl WorkerCostGuard { + fn for_request(store: &Arc, request: &AgentRequest) -> Option { + let openrouter = request + .provider + .as_ref() + .is_some_and(|provider| provider.target.kind == ProviderKind::OpenRouter); + openrouter.then(|| Self::begin(store, request.job_id)) + } + + fn begin(store: &Arc, job_id: i64) -> Self { + if let Err(err) = store.begin_cost_lookup(job_id) { + tracing::error!("job {job_id}: {err}"); + } + Self { + store: Arc::clone(store), + job_id, + } + } +} + +impl Drop for WorkerCostGuard { + fn drop(&mut self) { + if let Err(err) = self.store.end_cost_lookup(self.job_id) { + tracing::error!("job {}: {err}", self.job_id); + } + } +} + /// The server and tool of an agent's `mcp____` tool name when the /// server is one of the run's stdio servers. Server names hold no underscore, so /// the first `__` after the prefix ends the server. @@ -1042,8 +1079,9 @@ impl Scheduler { }; let scheduler = Arc::clone(self); let settings = settings.clone(); - let job = job.clone(); + let guard = WorkerCostGuard::for_request(&self.store, &request); self.spawn(row.id, Kind::Worker, async move { + let _guard = guard; scheduler.agent(&settings, request, skipped, job).await; }); } diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index cd8d703..cc98273 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -10516,6 +10516,7 @@ async fn a_charge_for_a_run_cancelled_before_its_report_stays_on_the_run_step() let id = store.create("maestro", "alice", "Add a button").unwrap(); scheduler.tick().await.unwrap(); store.apply(id, Event::Cancel).unwrap(); + assert!(store.cost_lookup_pending(id).unwrap()); executor.release(1); openrouter_finished(&store, id, 1).await; diff --git a/docs/design.md b/docs/design.md index f665f0b..3f28682 100644 --- a/docs/design.md +++ b/docs/design.md @@ -463,7 +463,7 @@ No OpenRouter key was available, so each CLI ran with the settings above against - The task takes a snapshot of the job before the run's result is applied. `add_fetched_cost` files the `cost` event under that snapshot's stage and pull request index, so a lookup that ends after the job moved on charges the step that ran. `timeline::build` adds a `cost` event's amount to the step of its own stage and never treats it as a transition, so the current step stays as it is. - A zero shows as `$0.00` only when `fetched` is set, that is, OpenRouter confirmed a free run, or when a Local session has a CLI. A plain zero from a subscription run in the same job stays a dash, even when an OpenRouter session started and its lookup failed. -- `begin_cost_lookup` writes the job to the `cost_lookups` table before the task spawns and `end_cost_lookup` removes it when the task ends. The job page polls its fragment while the job is live or has a row there, so a failed or merged job still shows a late charge and log line without a reload. The table lives in SQLite because the browser tests change state from a second process. `main` clears it before the scheduler starts, since a restart ends every task. +- The scheduler also counts an OpenRouter worker in `cost_lookups` from its dispatch until it ends or a cancel aborts it, so a page rendered after a cancel keeps polling for the charge. `begin_cost_lookup` writes the job to the `cost_lookups` table before the task spawns and `end_cost_lookup` removes it when the task ends. The job page polls its fragment while the job is live or has a row there, so a failed or merged job still shows a late charge and log line without a reload. The table lives in SQLite because the browser tests change state from a second process. `main` clears it before the scheduler starts, since a restart ends every task. Criterion 21, one run per CLI against OpenRouter with a real key, is not met by this pull request. From 046846f0762ff94ea0189dc254a341490a37d4a1 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:26:02 +0000 Subject: [PATCH 6/7] factory-server: register the worker lookup only for a live job A cancel while the agent request was built left a terminal page with no poller, and the scheduler then started the worker from a stale snapshot. The registration now checks the job's stage under the store lock and starts no worker when it changed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/scheduler.rs | 59 +++++++++++++++++------- crates/factory-server/src/store.rs | 21 +++++++++ crates/factory-server/tests/scheduler.rs | 13 ++++++ docs/design.md | 2 +- 4 files changed, 77 insertions(+), 18 deletions(-) diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index d033d24..fe32c1f 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -857,21 +857,31 @@ struct WorkerCostGuard { } impl WorkerCostGuard { - fn for_request(store: &Arc, request: &AgentRequest) -> Option { + /// `Ok(None)` for a run that is not on `OpenRouter`. `Err(())` when the job + /// left the stage it was dispatched in, so the run must not start. + fn for_request( + store: &Arc, + request: &AgentRequest, + dispatched: &Job, + ) -> Result, ()> { let openrouter = request .provider .as_ref() .is_some_and(|provider| provider.target.kind == ProviderKind::OpenRouter); - openrouter.then(|| Self::begin(store, request.job_id)) - } - - fn begin(store: &Arc, job_id: i64) -> Self { - if let Err(err) = store.begin_cost_lookup(job_id) { - tracing::error!("job {job_id}: {err}"); + if !openrouter { + return Ok(None); } - Self { - store: Arc::clone(store), - job_id, + let job_id = request.job_id; + match store.begin_cost_lookup_at(job_id, dispatched) { + Ok(true) => Ok(Some(Self { + store: Arc::clone(store), + job_id, + })), + Ok(false) => Err(()), + Err(err) => { + tracing::error!("job {job_id}: {err}"); + Ok(None) + } } } } @@ -1077,13 +1087,7 @@ impl Scheduler { else { continue; }; - let scheduler = Arc::clone(self); - let settings = settings.clone(); - let guard = WorkerCostGuard::for_request(&self.store, &request); - self.spawn(row.id, Kind::Worker, async move { - let _guard = guard; - scheduler.agent(&settings, request, skipped, job).await; - }); + self.spawn_agent(row.id, &settings, request, skipped, job); } Command::RunChecks { pr } => { self.checks(&row, pr, &job, &project, &settings, workers_free)?; @@ -2480,6 +2484,27 @@ impl Scheduler { } } + /// Starts the worker for `job`, unless the job left the stage it was + /// dispatched in, such as by a cancel while the request was built. + fn spawn_agent( + self: &Arc, + id: i64, + settings: &Settings, + request: AgentRequest, + skipped: Vec, + job: Job, + ) { + let Ok(guard) = WorkerCostGuard::for_request(&self.store, &request, &job) else { + return; + }; + let scheduler = Arc::clone(self); + let settings = settings.clone(); + self.spawn(id, Kind::Worker, async move { + let _guard = guard; + scheduler.agent(&settings, request, skipped, job).await; + }); + } + /// Writes the notices that precede a run's own output, the Local run line /// first. fn open_run_log( diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index 2665be0..381e8f8 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -2587,6 +2587,27 @@ impl Store { Ok(()) } + /// Like [`Self::begin_cost_lookup`], but only while job `id` is still in + /// the stage of `seen`. The check and the insert hold the connection, so a + /// cancel cannot land between them. Returns whether it registered. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn begin_cost_lookup_at(&self, id: i64, seen: &Job) -> Result { + let conn = self.conn(); + let now = Self::load(&conn, id)?; + if now.job.stage() != seen.stage() { + return Ok(false); + } + conn.execute( + "INSERT INTO cost_lookups (job_id, pending) VALUES (?1, 1) + ON CONFLICT (job_id) DO UPDATE SET pending = pending + 1", + [id], + )?; + Ok(true) + } + /// Marks that a lookup begun with [`Self::begin_cost_lookup`] is over. /// /// # Errors diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index cc98273..29bb93a 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -10529,3 +10529,16 @@ async fn a_charge_for_a_run_cancelled_before_its_report_stays_on_the_run_step() assert_eq!(cost.stage, "clarifying"); assert_eq!(cost.usd, Some(0.4)); } + +#[tokio::test] +async fn a_lookup_is_not_registered_for_a_job_cancelled_since_its_snapshot() { + let (store, _executor, _scheduler) = setup(|_| questions()); + let id = store.create("maestro", "alice", "Add a button").unwrap(); + let seen = store.start(id).unwrap().unwrap().job; + assert!(store.begin_cost_lookup_at(id, &seen).unwrap()); + store.end_cost_lookup(id).unwrap(); + + store.apply(id, Event::Cancel).unwrap(); + assert!(!store.begin_cost_lookup_at(id, &seen).unwrap()); + assert!(!store.cost_lookup_pending(id).unwrap()); +} diff --git a/docs/design.md b/docs/design.md index 3f28682..4538757 100644 --- a/docs/design.md +++ b/docs/design.md @@ -463,7 +463,7 @@ No OpenRouter key was available, so each CLI ran with the settings above against - The task takes a snapshot of the job before the run's result is applied. `add_fetched_cost` files the `cost` event under that snapshot's stage and pull request index, so a lookup that ends after the job moved on charges the step that ran. `timeline::build` adds a `cost` event's amount to the step of its own stage and never treats it as a transition, so the current step stays as it is. - A zero shows as `$0.00` only when `fetched` is set, that is, OpenRouter confirmed a free run, or when a Local session has a CLI. A plain zero from a subscription run in the same job stays a dash, even when an OpenRouter session started and its lookup failed. -- The scheduler also counts an OpenRouter worker in `cost_lookups` from its dispatch until it ends or a cancel aborts it, so a page rendered after a cancel keeps polling for the charge. `begin_cost_lookup` writes the job to the `cost_lookups` table before the task spawns and `end_cost_lookup` removes it when the task ends. The job page polls its fragment while the job is live or has a row there, so a failed or merged job still shows a late charge and log line without a reload. The table lives in SQLite because the browser tests change state from a second process. `main` clears it before the scheduler starts, since a restart ends every task. +- The scheduler also counts an OpenRouter worker in `cost_lookups` from its dispatch until it ends or a cancel aborts it, so a page rendered after a cancel keeps polling for the charge. The registration checks, under the store lock, that the job is still in the stage the dispatch saw, and a job cancelled since then starts no worker. `begin_cost_lookup` writes the job to the `cost_lookups` table before the task spawns and `end_cost_lookup` removes it when the task ends. The job page polls its fragment while the job is live or has a row there, so a failed or merged job still shows a late charge and log line without a reload. The table lives in SQLite because the browser tests change state from a second process. `main` clears it before the scheduler starts, since a restart ends every task. Criterion 21, one run per CLI against OpenRouter with a real key, is not met by this pull request. From 2ee3e95517ab560ae7fa6dac841107776150c1a3 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:34:02 +0000 Subject: [PATCH 7/7] factory-server: defer an OpenRouter worker when registration fails A store error while registering the lookup started the worker with no pending marker. The scheduler now logs it and retries on the next pass. A dashboard test loads the cancelled job page after registration and checks it polls until the charge shows in the fragment. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/scheduler.rs | 5 +++-- crates/factory-server/tests/dashboard.rs | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index fe32c1f..1b39851 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -858,7 +858,8 @@ struct WorkerCostGuard { impl WorkerCostGuard { /// `Ok(None)` for a run that is not on `OpenRouter`. `Err(())` when the job - /// left the stage it was dispatched in, so the run must not start. + /// left the stage it was dispatched in or the store failed, so the run does + /// not start and the next pass retries. fn for_request( store: &Arc, request: &AgentRequest, @@ -880,7 +881,7 @@ impl WorkerCostGuard { Ok(false) => Err(()), Err(err) => { tracing::error!("job {job_id}: {err}"); - Ok(None) + Err(()) } } } diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index 8ddd3ce..cc8da62 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -19364,3 +19364,26 @@ async fn the_review_card_offers_fix_elsewhere_for_a_fork_and_the_job_page_links_ assert!(page.body.contains("stacked-pr"), "{}", page.body); assert!(page.body.contains("/pull/77"), "{}", page.body); } + +#[tokio::test] +async fn a_cancelled_job_page_polls_until_the_registered_charge_arrives() { + let dashboard = dashboard(); + let id = dashboard.new_job().await; + dashboard.apply(id, Event::Start); + let at = dashboard.store.get(id).unwrap().job; + assert!(dashboard.store.begin_cost_lookup_at(id, &at).unwrap()); + dashboard.apply(id, Event::Cancel); + + let path = format!("/jobs/{id}"); + let page = dashboard.get(&path).await; + assert!( + page.body + .contains(&format!("hx-get=\"/jobs/{id}/fragment\"")) + ); + + dashboard.store.add_fetched_cost(id, 0.4, &at).unwrap(); + dashboard.store.end_cost_lookup(id).unwrap(); + let fragment = dashboard.get(&format!("{path}/fragment")).await; + assert!(fragment.body.contains("$0.40")); + assert!(!fragment.body.contains("hx-trigger")); +}