diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 322c280834..7e8f1e73c7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1130,6 +1130,9 @@ Complete uncapped listings retire deleted file checkpoints without deleting thei `usage_ledger::store` owns `usage.sqlite3`, named by `hide_kit::layout::usage_store` under the core state directory. Normalized usage events contain native call identity, model, time, session, working folder, provider, tokens and recorded cost, with no conversation fields. +A stored call holds each of those once, in the columns its readers use (the calls format, with-hide/hide-private#672): its key as 32 bytes, its node by the number of a `nodes` row, its tokens and cost as numbers, and its session and working folder by the number of a `places` row, one per (node, agent, session, folder), where a call that named no folder keeps an empty one, which no folder can be. +Nothing reads a call but the dedup lookup, a Claude call's later view, the projects' costs and the pruning, and none of them needs the whole event, so a call is about a fifth of the whole-event JSON version 3 kept beside a hexadecimal key: the operator's 638,000-call store of 512 MiB was 96 MiB converted and compacted (19%), under the 512 MiB bound with five machines of that history. +Whether a later view bills the same call is read from the stored values (time, model, tokens, cost, provider, incomplete), the same values version 3 hashed into a fingerprint column it no longer needs. An ingestion transaction adds a new call and its daily `(native node, agent, local day, model)` totals together with the file checkpoint; repeated calls add nothing, and changed completed calls keep the first accounting value and report a count-only conflict. Claude streaming records retain each token field's maximum for that native call, replacing its daily contribution and whole-call pricing band in the same transaction without another call; a later view that raises no maximum writes nothing and counts as a repeat. A persisted checkpoint distinguishes a yielded read from EOF, so a restart cannot freeze an unread suffix. @@ -1140,11 +1143,25 @@ New calls use the current core time zone. Each agent's first backfill may fill older days within the 400-day retention window, and its event keys stay until that backfill's durable completion marker is written. After completion, whole days before the 45-day event horizon are frozen: replayed or late calls before that boundary are counted as skipped and never change those totals. The boundary is retained as a monotonic instant so a clock rollback or time-zone change cannot admit a call whose dedup key already expired. -Maintenance removes at most 512 expired events and 512 expired daily rows per turn; the event bound is one million per native node, the candidate bound 10,000 per agent, the daily-row bound 100,000, the native-node bound 32 and the database bound 512 MiB, with each refusal reported rather than silently growing storage. +Maintenance removes at most 512 expired calls, 512 places and 512 expired daily rows per turn; the call bound is one million per native node, the candidate bound 10,000 per agent, the daily-row bound 100,000, the native-node bound 32 and the database bound 512 MiB, with each refusal reported rather than silently growing storage. +A place keeps its newest call's time and is pruned once that call and every other expired call of its agent are gone, so a place outlives no call of its own and a node's places never outnumber its calls. The store uses SQLite WAL and full synchronous commits, refuses a damaged or newer store without rebuilding it, and travels with `MOVES_WITH_CORE` through the existing consistent SQLite copy. -The `events_device_at` index on `(device, at)` serves the projects' costs below; like the Hide AI tables it is created `IF NOT EXISTS` on open without raising `user_version`, so a build from before it still opens the store and keeps the index current, where a version bump would make that build refuse the store (`usage_store_newer`) and lose its usage after a rollback. -Building it on an existing store reads every event once, about a second for 486,000 events on a loaded machine, so it runs under its own 30-second budget rather than an open's 250 ms one. -The read orders calls of one time by agent and key, which SQLite sorts one time at a time (at most 21 calls in the operator's store); an index holding agent and key too was 62 MB against this one's 25 MB. +The `calls_node_at` index on `(node, at DESC)` serves the projects' costs below and the pruning; beside a table without rowids it carries the primary key `(node, agent, key)` too, ascending after the newest-first time, so a read of a node's newest calls ordered by time, agent and key sorts nothing. + +A version 3 store is converted in place, never rebuilt, and never all at once. +Its first open by a build of the calls format adds the new tables and a node for each device in one transaction and leaves `events` and its indexes as they were; the device's count in `devices` stays the one count of its calls in both tables, which a move leaves alone; from then on the worker moves at most 4,096 calls a step, each step one transaction that deletes them from `events` and writes them as calls (`Store::convert`), until `events` is empty. +Until `events` is empty the worker reads, counts and prunes no call and the projects' costs stay pending, since a call still waiting in `events` would not be found as already counted; the daily totals and Hide AI's tables stay readable throughout. +A step that fails or is ended changes nothing, and the next step, in the same process or after a restart or a core move, takes the same calls again; a damaged call fails its step with its cause, logged and on the usage page, and is tried again a minute later rather than skipped. +The operator's 638,000 calls took 156 steps, 92 seconds in all and 2.1 seconds the slowest, on a Mac running other builds at the same time. +Moving leaves the old calls' pages free, and SQLite reuses free pages but never returns them, so whenever more than half the file is free pages, after a conversion or at any open, the worker compacts it once with `VACUUM` and empties the write-ahead log (`Store::compact`, its own two-minute budget, four seconds for the operator's store on that Mac); a compaction that fails is logged and the store stays as it was, larger, until the next open tries again. + +Going back to a build from before the calls format, at any point and halfway through a conversion too, keeps every record this build wrote and every count true, and coming back within 45 days counts each call made in between once; outside that rule are a longer stay and a session file its agent removed in the meantime (Claude Code removes a session 30 days after its last activity unless `cleanupPeriodDays` says otherwise), whose calls are not counted. +A device at its limit of a million calls is outside it too: the older build skips the stay's calls past the limit as it always has, marks the agent limited and logs `usage_event_capacity`, and this build does not count them again. +The store's version stays 3, the oldest layout a build reads and writes it correctly in, and every table a version 3 build uses stays as it made it, `events` empty, so such a build opens the store as its own and records Hide AI's calls into `ai_daily`, which the calls format did not change. +A native call it would count goes into `events`, which it reads to find a call already counted and which no longer holds one, so it could count a call this build already counted; the store refuses that write (the trigger `events_closed`), and the refusal rolls back the older build's whole ingest, checkpoint included, so it counts no native call while it runs and its usage page says the ledger failed. +It still finds, merges a later view into and prunes the calls a halfway conversion left in `events` as it always did, taking each it prunes off the device's count in `devices`, which counts the device's calls in both tables, so the count stays the number of calls there are and the limit of a million calls a device is one value for both formats (`an_older_build_pruning_a_halfway_conversion_keeps_one_true_count`). +Back on this build the conversion goes on, and the stay's calls are read from their native files after the checkpoints this build left and counted once, a later view of a call already counted merged as ever (`an_older_build_counts_no_call_into_a_converted_store_and_the_return_counts_each_once`). +A change that keeps an older build able to open the store adds its tables, indexes and refusals beside the ones it uses without raising the version, as Hide AI's tables and the calls format do; one an older build would misread raises it, and that build then refuses the store (`usage_store_newer`) and loses Hide AI's calls of that time when it exits. Native physical node identities and their qualified source paths stay unchanged when the core's owner changes. The same store retains the public price cache and the last network-attempt time; that state moves with the ledger so a core move cannot bypass the daily fetch bound. @@ -1172,7 +1189,7 @@ A local agent that stops working has its project's worktrees read again (`read_w The detail item `remains` names a worktree; while it is the shown top of the 보기 slot and no Changes surface is visible, `changes_target` reads that worktree's changes, in front or not. A project's cost (`usage_ledger/project_cost.rs`) is prepared on the ledger worker, never under `Mutex`. -The runtime tells the worker each local, non-Home project's checkout paths (`feed_usage_projects`, on a catalog replacement, notifying only on a change); the worker reads the last eight days of its own node's `events` (`store::recent_calls`, newest first by `events_device_at` and calls of one time by agent and key, a total order since `(device, agent, key)` is the primary key, so a capped read keeps the same calls under any plan; at most `EVENT_LIMIT` 200,000 calls with a two-second progress budget, `limited` past it), keeps the seven days ending today, gives a call to the project whose deepest checkout holds its session's folder (`files::path_inside_root`, decided once per folder), and prices each (agent, day, model) and (agent, session, model) group with `prices::cost` as a day is priced. +The runtime tells the worker each local, non-Home project's checkout paths (`feed_usage_projects`, on a catalog replacement, notifying only on a change); the worker reads the last eight days of its own node's `calls` (`store::recent_calls`, newest first by `calls_node_at` and calls of one time by agent and key, a total order since `(node, agent, key)` is the primary key, so a capped read keeps the same calls under any plan; at most `EVENT_LIMIT` 200,000 calls with a two-second progress budget, `limited` past it), keeps the seven days ending today, gives a call to the project whose deepest checkout holds its session's folder (`files::path_inside_root`, decided once per folder), and prices each (agent, day, model) and (agent, session, model) group with `prices::cost` as a day is priced. Each call is decoded, added to its groups by `project_cost::Preparation` and dropped, so a build holds the groups and the folder owners, not the calls. It rebuilds when the projects or the day change, and when ingestion added or rewrote a call of those eight days or a new price table dirtied it, at most once per `COST_REBUILD` (30 s); a backfill of older history and pruning, which removes only calls past the 45-day horizon, leave it as built; a failed build keeps the last value, stays due, is tried again after the same wait and logs each new cause once. The result rides the usage frame as `nodes[].projects`, absent until a build succeeded so a tile tells a cost not read yet from a read that found nothing (B33), with `projects_failed` while the latest build failed or the usage store did not open; a project that ran no call is not listed, and an agent with an unpriced call is named in `unpriced_agents` with its priced calls still summed and the total marked `partial`; the daily totals, the Overview's Usage and the calendars below are unchanged, and a project on a connected device has no cost here. diff --git a/hide-core/src/usage_ledger/project_cost.rs b/hide-core/src/usage_ledger/project_cost.rs index 289c71b83f..c81b6a36c6 100644 --- a/hide-core/src/usage_ledger/project_cost.rs +++ b/hide-core/src/usage_ledger/project_cost.rs @@ -1,5 +1,5 @@ //! A project's last seven days of cost (PRD lane-two-columns D-19, B31), -//! prepared on the ledger worker from the 45-day `events` table: the calls +//! prepared on the ledger worker from the 45-day `calls` table: the calls //! whose session ran inside one of the project's checkouts, priced the way a //! day is (`prices::cost`). The daily totals and the Overview's Usage are //! untouched; a call outside every checkout counts for no project. diff --git a/hide-core/src/usage_ledger/store.rs b/hide-core/src/usage_ledger/store.rs index 40c739f90e..3750b37a40 100644 --- a/hide-core/src/usage_ledger/store.rs +++ b/hide-core/src/usage_ledger/store.rs @@ -1,8 +1,24 @@ -//! Events, daily totals and checkpoints are one transaction. After the first +//! Calls, daily totals and checkpoints are one transaction. After the first //! backfill, days outside the event horizon are frozen and never added again. //! A damaged store is refused, never rebuilt: its old daily totals may be //! the only remaining record after an agent deletes its source history. +//! +//! A call row holds each value its readers need once (with-hide/hide-private#672): +//! its key as 32 bytes, its node by number, its tokens as numbers and its +//! session and folder by the number of a `places` row, so a call costs about +//! a fifth of the whole-event JSON a version 3 store kept. A version 3 store +//! is converted in place, a batch per step ([`Store::convert`]), and then +//! compacted once ([`Store::compact`]). +//! +//! A build from before this format opens a converted store as it opens its +//! own: the version stays 3 and every table it uses stays, `events` empty. +//! It records Hide AI's calls into `ai_daily` as before, but `events` +//! refuses its write of a native call, which it could not tell from one +//! this build already counted; the refusal rolls its whole ingest back, +//! checkpoint included, so the call waits in its native file and this +//! build counts it once on return. +use std::collections::HashMap; use std::path::Path; use std::time::{Duration, Instant}; @@ -10,19 +26,53 @@ use hide_session::{ Agent, usage::{Candidate, Checkpoint, Event, Step, Tokens}, }; -use rusqlite::{Connection, ErrorCode, OptionalExtension, params}; +use rusqlite::{Connection, ErrorCode, OptionalExtension, Row, params}; use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; use super::{DAILY_DAYS, DAILY_LIMIT, DAY_MS, EVENT_DAYS, EVENT_LIMIT, local_day}; mod ai; pub use ai::{AiPart, AiRecorded, AiRow, AiUnknown}; mod stream; +#[cfg(test)] +pub(crate) mod v3_fixture; +/// The oldest layout a build reads and writes this store correctly in. The +/// calls format did not raise it: every table a version 3 build uses is +/// still here, and `calls` beside them marks a converted store. const VERSION: i64 = 3; const DEVICE_LIMIT: usize = 32; const BATCH_LIMIT: usize = 8192; const CHECKPOINT_BYTES: usize = 16 * 1024; +/// The calls and what they name. `places` holds each (node, agent, session, +/// folder) a call ran in once, with the newest call's time, so the place +/// leaves with its last call ([`Store::prune`]); every place has had a call +/// of its own, so a node's places never outnumber its calls. A call's folder +/// is `''` when the native record named none, which no folder can be +/// (`valid_name`). `calls_node_at` serves the projects' costs and pruning; +/// beside a table without rowids it carries the primary key too, ascending +/// after the newest-first time, so a read ordered by time (newest first), +/// agent and key sorts nothing. `events_closed` refuses a call an older +/// build would write into `events`, so no call is ever counted in both. +/// A node names its device's calls by number; how many calls a device has +/// in both tables stays `devices.calls`, the one count either build reads +/// against its limit. +const CALLS_SCHEMA: &str = " +CREATE TABLE nodes(id INTEGER PRIMARY KEY, device TEXT NOT NULL UNIQUE); +CREATE TABLE places(id INTEGER PRIMARY KEY, node INTEGER NOT NULL, agent TEXT NOT NULL, + session TEXT NOT NULL, cwd TEXT NOT NULL, last_at INTEGER NOT NULL, + UNIQUE(node,agent,session,cwd)); +CREATE TABLE calls(node INTEGER NOT NULL, agent TEXT NOT NULL, key BLOB NOT NULL, + at INTEGER NOT NULL, day TEXT NOT NULL, model TEXT NOT NULL, place INTEGER NOT NULL, + provider TEXT, input INTEGER NOT NULL, output INTEGER NOT NULL, + cache_read INTEGER NOT NULL, cache_write INTEGER NOT NULL, + cache_write_1h INTEGER NOT NULL, reasoning INTEGER, cost INTEGER, + incomplete INTEGER NOT NULL, PRIMARY KEY(node,agent,key)) WITHOUT ROWID; +CREATE INDEX calls_node_at ON calls(node,at DESC); +CREATE TRIGGER events_closed BEFORE INSERT ON events + BEGIN SELECT RAISE(ABORT,'usage_calls_format'); END; +"; +/// The tables a version 3 build made, kept for one that opens this store: +/// a version 3 store has them, and a new store is made with them. const SCHEMA: &str = " CREATE TABLE events(device TEXT NOT NULL, agent TEXT NOT NULL, key TEXT NOT NULL, day TEXT NOT NULL, fingerprint BLOB NOT NULL, at INTEGER NOT NULL, @@ -41,6 +91,23 @@ CREATE TABLE devices(device TEXT PRIMARY KEY, calls INTEGER NOT NULL DEFAULT 0); CREATE TABLE price_cache(slot INTEGER PRIMARY KEY CHECK(slot=1), value TEXT NOT NULL); PRAGMA user_version=3; "; +/// A version 3 store gains the calls tables in one transaction that moves +/// no call: its `events` stay where they are, with their indexes, until +/// [`Store::convert`] has moved them all, so an older build that opens the +/// store halfway reads and prunes them as it always did. Each device +/// becomes a node; its count in `devices` already counts the calls a move +/// carries from one table to the other. +const START_CONVERSION: &str = "INSERT INTO nodes(device) SELECT device FROM devices;"; +/// The calls one conversion step moves, in one transaction: about half a +/// second on a loaded Mac, so 640,000 calls take one to two minutes of +/// steps while a window is open. +const CONVERT_BATCH: usize = 4096; +/// A conversion step's own budget: every step reads and writes thousands of +/// calls, past an ordinary step's 250 ms on a machine under load. +const CONVERT_BUDGET: Duration = Duration::from_secs(30); +/// Compacting rewrites the whole file once: four seconds for a converted +/// 640,000-call store on a loaded Mac. +const COMPACT_BUDGET: Duration = Duration::from_secs(120); /// Hide's own background AI, counted by day, provider, model and feature. /// Added beside the session tables without a version bump, so an older build @@ -53,21 +120,18 @@ CREATE TABLE IF NOT EXISTS ai_daily(day TEXT NOT NULL, provider TEXT NOT NULL, CREATE INDEX IF NOT EXISTS ai_daily_day ON ai_daily(day); CREATE TABLE IF NOT EXISTS ai_state(slot INTEGER PRIMARY KEY CHECK(slot=1), limited_day TEXT); "; -/// The projects' costs read one device's newest calls (`recent_calls`); with -/// only `events_at` SQLite sorted every call of the window in a temporary -/// tree. Added without a version bump, as `AI_SCHEMA` is, so an older build -/// opens the same file and keeps the index current. -const COST_INDEX: &str = "CREATE INDEX IF NOT EXISTS events_device_at ON events(device,at);"; -/// The own node's calls of a window, newest first. `(device, agent, key)` is +/// The own node's calls of a window, newest first. `(node, agent, key)` is /// the primary key, so the order is total: past the limit the same calls are -/// read whichever plan SQLite chooses. By `events_device_at` SQLite sorts -/// only the calls of one time, a few at most, where an index holding agent -/// and key too would be more than twice its size. -const RECENT_CALLS: &str = "SELECT agent,day,event FROM events WHERE device=?1 AND at>=?2 ORDER BY at DESC,agent,key LIMIT ?3"; -/// Building `events_device_at` on an existing store reads every call once: -/// about a second for 486,000 calls on a loaded machine, against a step's -/// 250 ms. -const INDEX_BUDGET: Duration = Duration::from_secs(30); +/// read whichever plan SQLite chooses, and by `calls_node_at` none is sorted. +const RECENT_CALLS: &str = "SELECT c.agent,c.day,c.key,c.at,c.model,c.input,c.output,c.cache_read,\ + c.cache_write,c.cache_write_1h,c.reasoning,c.cost,c.incomplete,c.provider,p.session,p.cwd \ + FROM calls c JOIN places p ON p.id=c.place \ + WHERE c.node=(SELECT id FROM nodes WHERE device=?1) AND c.at>=?2 \ + ORDER BY c.at DESC,c.agent,c.key LIMIT ?3"; +/// One stored call by its identity, with the day it was counted on. +const STORED_CALL: &str = "SELECT c.day,c.key,c.at,c.model,c.input,c.output,c.cache_read,\ + c.cache_write,c.cache_write_1h,c.reasoning,c.cost,c.incomplete,c.provider,p.session,p.cwd \ + FROM calls c JOIN places p ON p.id=c.place WHERE c.node=?1 AND c.agent=?2 AND c.key=?3"; /// Distinct (day, provider, model, feature) rows kept for Hide AI. About 400 /// days of four features, two providers and a few models each. pub const AI_ROW_LIMIT: usize = 40_000; @@ -245,7 +309,7 @@ impl Store { } store .connection - .execute_batch(&format!("BEGIN;{SCHEMA}COMMIT;")) + .execute_batch(&format!("BEGIN;{SCHEMA}{CALLS_SCHEMA}COMMIT;")) .map_err(failed)?; } else if version == 1 { store.connection.execute_batch("BEGIN; CREATE TABLE price_cache(slot INTEGER PRIMARY KEY CHECK(slot=1), value TEXT NOT NULL); PRAGMA user_version=2; COMMIT;").map_err(failed)?; @@ -253,9 +317,23 @@ impl Store { if version == 1 || version == 2 { store.connection.execute_batch("BEGIN; ALTER TABLE backfills ADD COLUMN limited INTEGER NOT NULL DEFAULT 0; PRAGMA user_version=3; COMMIT;").map_err(failed)?; } + let converted: bool = store + .connection + .query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='calls')", + [], + |r| r.get(0), + ) + .map_err(failed)?; + if !converted { + store.budget_of(CONVERT_BUDGET); + store + .connection + .execute_batch(&format!("BEGIN;{CALLS_SCHEMA}{START_CONVERSION}COMMIT;")) + .map_err(failed)?; + store.budget(); + } store.connection.execute_batch(AI_SCHEMA).map_err(failed)?; - store.budget_of(INDEX_BUDGET); - store.connection.execute_batch(COST_INDEX).map_err(failed)?; Ok(store) } @@ -414,7 +492,7 @@ impl Store { .optional() .map_err(failed)?; let mut calls = match calls { - Some(n) => n, + Some(calls) => calls, None => { let n: usize = tx .query_row("SELECT count(*) FROM devices", [], |r| r.get(0)) @@ -427,6 +505,14 @@ impl Store { 0 } }; + // An older build adds a device it meets to `devices` only. + tx.execute("INSERT OR IGNORE INTO nodes(device) VALUES(?1)", [device]) + .map_err(failed)?; + let node: i64 = tx + .query_row("SELECT id FROM nodes WHERE device=?1", [device], |r| { + r.get(0) + }) + .map_err(failed)?; let known: bool = tx .query_row( "SELECT EXISTS(SELECT 1 FROM cursors WHERE device=?1 AND agent=?2 AND path=?3)", @@ -473,27 +559,25 @@ impl Store { let mut outcome = Ingested::default(); for event in &step.events { validate(event)?; - let fingerprint = fingerprint(event)?; if event.at_ms > now.saturating_add(DAY_MS) { outcome.invalid += 1; continue; } - let previous: Option<(Vec, String)> = tx - .query_row( - "SELECT fingerprint,event FROM events WHERE device=?1 AND agent=?2 AND key=?3", - params![device, agent.as_str(), event.key], - |r| Ok((r.get(0)?, r.get(1)?)), - ) + let key = key_bytes(&event.key)?; + let previous = tx + .query_row(STORED_CALL, params![node, agent.as_str(), key], |row| { + Ok((row.get::<_, String>(0)?, stored_call(row, 1))) + }) .optional() .map_err(failed)?; - if let Some((previous, original)) = previous { - if previous == fingerprint { + if let Some((day, original)) = previous { + let original = original?; + if same_accounting(&original, event) { outcome.repeated += 1; continue; } - let original: Event = decode(&original)?; let merged = if agent == Agent::Claude { - stream::merge(&tx, device, &original, event, frozen_at)? + stream::merge(&tx, device, node, &day, &original, event, frozen_at)? } else { None }; @@ -539,19 +623,7 @@ impl Store { totals.add(event)?; tx.execute("INSERT INTO daily VALUES(?1,?2,?3,?4,?5) ON CONFLICT(device,agent,day,model) DO UPDATE SET totals=excluded.totals", params![device,agent.as_str(),day,event.model,encode(&totals)?]).map_err(failed)?; - tx.execute( - "INSERT INTO events VALUES(?1,?2,?3,?4,?5,?6,?7)", - params![ - device, - agent.as_str(), - event.key, - day, - fingerprint, - event.at_ms, - encode(event)? - ], - ) - .map_err(failed)?; + insert_call(&tx, node, agent.as_str(), &day, event)?; calls += 1; outcome.added += 1; outcome.newest_ms = outcome.newest_ms.max(Some(event.at_ms)); @@ -610,8 +682,8 @@ impl Store { /// `RECENT_CALLS` order, with their agent and assigned day, for the /// projects' costs (PRD lane-two-columns B31), and says whether more than /// `limit` were there. Each call is decoded, handed on and dropped, so nothing here - /// grows with the calls read. It reads the 45-day `events` table by - /// `events_device_at`, with a longer budget than a step's because it + /// grows with the calls read. It reads the 45-day `calls` table by + /// `calls_node_at`, with a longer budget than a step's because it /// decodes every call, `each` included; the caller keeps the days it /// wants. pub fn recent_calls( @@ -638,7 +710,7 @@ impl Store { .as_str() .map_err(|_| "usage_store_decode") }; - each(text(0)?, text(1)?, decode(text(2)?)?)?; + each(text(0)?, text(1)?, stored_call(row, 2)?)?; read += 1; } Ok(false) @@ -684,23 +756,64 @@ impl Store { [&frozen], ) .map_err(failed)?; - // A maintenance turn deletes at most 512 calls and 512 rollups. - // Adjust the retained counter from those exact rows, never COUNT an - // entire million-call device on each wake. - let expired = { - let mut query=tx.prepare("SELECT e.rowid,e.device FROM events e WHERE e.at = { + let mut query = tx + .prepare("SELECT id,device FROM nodes ORDER BY id") + .map_err(failed)?; query - .query_map([frozen], |r| { - Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)) - }) + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) .map_err(failed)? - .collect::, _>>() + .collect::>() .map_err(failed)? }; - for (id, device) in &expired { - tx.execute("DELETE FROM events WHERE rowid=?1", [id]) + let (mut expired, mut places) = (0, 0); + for (node, device) in &nodes { + if expired == 512 || places == 512 { + break; + } + let keys: Vec<(String, Vec)> = { + let mut query = tx + .prepare( + "SELECT agent,key FROM calls WHERE node=?1 AND at>() + .map_err(failed)? + }; + for (agent, key) in &keys { + tx.execute( + "DELETE FROM calls WHERE node=?1 AND agent=?2 AND key=?3", + params![node, agent, key], + ) .map_err(failed)?; - tx.execute("UPDATE devices SET calls=calls-1 WHERE device=?1", [device]) + } + tx.execute( + "UPDATE devices SET calls=calls-?2 WHERE device=?1", + params![device, keys.len()], + ) + .map_err(failed)?; + expired += keys.len(); + // A place whose newest call expired has no call left once its + // agent's expired calls are all gone. + places += tx + .execute( + "DELETE FROM places WHERE id IN(SELECT p.id FROM places p WHERE p.node=?1 \ + AND p.last_at Result { + self.budget(); + self.connection + .query_row("SELECT EXISTS(SELECT 1 FROM events)", [], |r| r.get(0)) + .map_err(failed) + } + + /// Moves the next version 3 calls into `calls`, at most + /// [`CONVERT_BATCH`], in one transaction; answers how many it moved. + /// `events` stays, empty, for an older build to open. A step that fails + /// or is ended changes nothing, so the next one, in this process or + /// after a restart, takes the same calls again. + pub fn convert(&mut self) -> Result { + self.budget_of(CONVERT_BUDGET); + let moved = self.convert_batch(); + self.budget(); + moved + } + + fn convert_batch(&mut self) -> Result { + let tx = self.connection.transaction().map_err(failed)?; + type Old = (i64, String, String, String, String, String); + let rows: Vec = { + let mut query = tx + .prepare( + "SELECT rowid,device,agent,key,day,event FROM events ORDER BY rowid LIMIT ?1", + ) + .map_err(failed)?; + query + .query_map([CONVERT_BATCH], |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + )) + }) + .map_err(failed)? + .collect::>() + .map_err(failed)? + }; + // Freed first, so the batch's new rows reuse the pages its old rows + // leave in a store at its page limit. + if let Some((last, ..)) = rows.last() { + tx.execute("DELETE FROM events WHERE rowid<=?1", [last]) + .map_err(failed)?; + } + let mut nodes = HashMap::new(); + for (_, device, agent, key, day, event) in &rows { + let node = match nodes.get(device) { + Some(node) => *node, + None => { + let node: i64 = tx + .query_row("SELECT id FROM nodes WHERE device=?1", [device], |r| { + r.get(0) + }) + .optional() + .map_err(failed)? + .ok_or("usage_store_inconsistent")?; + nodes.insert(device.clone(), node); + node + } + }; + let mut event: Event = decode(event)?; + // The key column was the call's identity; the copy inside the + // event is the one that goes. + event.key = key.clone(); + validate(&event)?; + insert_call(&tx, node, agent, day, &event)?; + } + tx.commit().map_err(failed)?; + Ok(rows.len()) + } + + /// Whether more than half the file is free pages, as a conversion or a + /// long quiet spell of pruning leaves it: SQLite reuses free pages but + /// never gives them back on its own. + pub fn compaction_due(&self) -> Result { + self.budget(); + let pages: u64 = self + .connection + .pragma_query_value(None, "page_count", |r| r.get(0)) + .map_err(failed)?; + let free: u64 = self + .connection + .pragma_query_value(None, "freelist_count", |r| r.get(0)) + .map_err(failed)?; + Ok(free * 2 > pages) } + + /// Rewrites the file without its free pages and empties the write-ahead + /// log, so the disk holds what the store keeps. One `VACUUM`: ended or + /// failed, the store stays as it was. + pub fn compact(&mut self) -> Result<(), &'static str> { + self.budget_of(COMPACT_BUDGET); + let compacted = self + .connection + .execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);") + .map_err(failed); + self.budget(); + compacted + } +} + +/// A call's key as the 32 bytes its 64 hex digits spell (`validate` +/// checked them). +fn key_bytes(key: &str) -> Result, &'static str> { + (0..key.len()) + .step_by(2) + .map(|at| { + key.get(at..at + 2) + .and_then(|pair| u8::from_str_radix(pair, 16).ok()) + .ok_or("usage_key_invalid") + }) + .collect() +} + +/// Stores `event` as one call of `node`'s `agent` counted on `day`, and its +/// place, which keeps the newest call's time. +fn insert_call( + tx: &rusqlite::Transaction<'_>, + node: i64, + agent: &str, + day: &str, + event: &Event, +) -> Result<(), &'static str> { + let place: i64 = tx + .query_row( + "INSERT INTO places(node,agent,session,cwd,last_at) VALUES(?1,?2,?3,?4,?5) \ + ON CONFLICT(node,agent,session,cwd) DO UPDATE SET last_at=max(last_at,excluded.last_at) \ + RETURNING id", + params![ + node, + agent, + event.session, + event.cwd.as_deref().unwrap_or(""), + event.at_ms + ], + |r| r.get(0), + ) + .map_err(failed)?; + let tokens = &event.tokens; + tx.execute( + "INSERT INTO calls VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16)", + params![ + node, + agent, + key_bytes(&event.key)?, + event.at_ms, + day, + event.model, + place, + event.provider, + tokens.input, + tokens.output, + tokens.cache_read, + tokens.cache_write, + tokens.cache_write_1h, + tokens.reasoning, + event.recorded_cost_micro_usd, + event.incomplete, + ], + ) + .map_err(failed)?; + Ok(()) +} + +/// The call whose columns start at `from` in `row`, in `STORED_CALL`'s +/// order: key, time, model, tokens, cost, incomplete, provider, session, +/// folder. +fn stored_call(row: &Row<'_>, from: usize) -> Result { + let at = |index: usize| from + index; + let key: Vec = row.get(at(0)).map_err(failed)?; + if key.len() != 32 { + return Err("usage_store_decode"); + } + let cwd: String = row.get(at(13)).map_err(failed)?; + Ok(Event { + key: key.iter().map(|byte| format!("{byte:02x}")).collect(), + at_ms: row.get(at(1)).map_err(failed)?, + model: row.get(at(2)).map_err(failed)?, + tokens: Tokens { + input: row.get(at(3)).map_err(failed)?, + output: row.get(at(4)).map_err(failed)?, + cache_read: row.get(at(5)).map_err(failed)?, + cache_write: row.get(at(6)).map_err(failed)?, + cache_write_1h: row.get(at(7)).map_err(failed)?, + reasoning: row.get(at(8)).map_err(failed)?, + }, + recorded_cost_micro_usd: row.get(at(9)).map_err(failed)?, + incomplete: row.get(at(10)).map_err(failed)?, + provider: row.get(at(11)).map_err(failed)?, + session: row.get(at(12)).map_err(failed)?, + cwd: (!cwd.is_empty()).then_some(cwd), + }) +} + +/// Whether `next` bills what the stored call billed. A fork may change the +/// containing session or cwd; neither changes the billed call. A completed +/// call's accounting stays pinned while its call exists; the frozen-day +/// boundary protects it after expiry. +fn same_accounting(stored: &Event, next: &Event) -> bool { + stored.at_ms == next.at_ms + && stored.model == next.model + && stored.tokens == next.tokens + && stored.recorded_cost_micro_usd == next.recorded_cost_micro_usd + && stored.provider == next.provider + && stored.incomplete == next.incomplete } fn freeze_at(now: u64, zone: &jiff::tz::TimeZone) -> Result { @@ -789,23 +1119,5 @@ fn decode(text: &str) -> Result serde_json::from_str(text).map_err(|_| "usage_store_decode") } -fn fingerprint(event: &Event) -> Result, &'static str> { - // A fork may change the containing session or cwd; neither changes the - // billed call. A completed call's accounting stays pinned while its - // event exists; the frozen-day boundary protects it after expiry. - Ok(Sha256::digest( - encode(&( - event.at_ms, - &event.model, - &event.tokens, - event.recorded_cost_micro_usd, - &event.provider, - event.incomplete, - ))? - .as_bytes(), - ) - .to_vec()) -} - #[cfg(test)] mod tests; diff --git a/hide-core/src/usage_ledger/store/stream.rs b/hide-core/src/usage_ledger/store/stream.rs index a72d3cbbef..e8cbd6c1e5 100644 --- a/hide-core/src/usage_ledger/store/stream.rs +++ b/hide-core/src/usage_ledger/store/stream.rs @@ -31,10 +31,14 @@ pub(super) enum Merged { } /// `None` when `next` is not a later view of `old` but another call under -/// the same key. +/// the same key. `old` is `node`'s Claude call stored as counted on `day`: +/// changing the machine's timezone must not move an already accounted call +/// into another rollup. pub(super) fn merge( tx: &rusqlite::Transaction<'_>, device: &str, + node: i64, + day: &str, old: &Event, next: &Event, frozen_at: u64, @@ -66,15 +70,6 @@ pub(super) fn merge( if merged == *old { return Ok(Some(Merged::Same)); } - // Read the persisted original day: changing the machine's timezone must - // not move an already accounted call into another rollup. - let day: String = tx - .query_row( - "SELECT day FROM events WHERE device=?1 AND agent='claude' AND key=?2", - params![device, old.key], - |row| row.get(0), - ) - .map_err(failed)?; let raw: String = tx .query_row( "SELECT totals FROM daily WHERE device=?1 AND agent='claude' AND day=?2 AND model=?3", @@ -108,9 +103,20 @@ pub(super) fn merge( params![device, day, old.model, encode(&totals)?], ) .map_err(failed)?; + let tokens = &merged.tokens; tx.execute( - "UPDATE events SET event=?3,fingerprint=?4 WHERE device=?1 AND agent='claude' AND key=?2", - params![device, old.key, encode(&merged)?, fingerprint(&merged)?], + "UPDATE calls SET input=?3,output=?4,cache_read=?5,cache_write=?6,cache_write_1h=?7,\ + reasoning=?8 WHERE node=?1 AND agent='claude' AND key=?2", + params![ + node, + key_bytes(&old.key)?, + tokens.input, + tokens.output, + tokens.cache_read, + tokens.cache_write, + tokens.cache_write_1h, + tokens.reasoning + ], ) .map_err(failed)?; Ok(Some(Merged::Rewrote)) diff --git a/hide-core/src/usage_ledger/store/tests.rs b/hide-core/src/usage_ledger/store/tests.rs index bad5c2158c..f3fed5e072 100644 --- a/hide-core/src/usage_ledger/store/tests.rs +++ b/hide-core/src/usage_ledger/store/tests.rs @@ -1,3 +1,4 @@ +use super::v3_fixture::{V3, count_as_version_3, kept_rows, prune_as_version_3}; use super::*; /// The store's step budgets are the worker's; these tests read what a step @@ -93,12 +94,15 @@ fn claude_streaming_maxima_replace_one_call_and_its_context_band() { ); assert_eq!(totals.price_bands[1].input, 0); assert_eq!(totals.price_bands[2].input, 210_000); - let saved: String = store + let saved: (String, String) = store .connection - .query_row("SELECT event FROM events", [], |row| row.get(0)) + .query_row( + "SELECT p.session,p.cwd FROM calls c JOIN places p ON p.id=c.place", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) .unwrap(); - let saved: Event = decode(&saved).unwrap(); - assert_eq!((saved.session, saved.cwd), (old.session, old.cwd)); + assert_eq!(saved, (old.session, old.cwd.unwrap())); } #[test] @@ -175,8 +179,7 @@ fn price_bands_reprice_expired_calls_and_daily_fetch_attempt_survives_restart() assert_eq!( store .connection - .query_row("SELECT count(*) FROM events", [], |row| row - .get::<_, u64>(0)) + .query_row("SELECT count(*) FROM calls", [], |row| row.get::<_, u64>(0)) .unwrap(), 0 ); @@ -219,26 +222,18 @@ fn price_bands_reprice_expired_calls_and_daily_fetch_attempt_survives_restart() fn price_cache_upgrade_preserves_existing_ledger_and_does_not_fetch() { let dir = tempfile::tempdir().unwrap(); let path = hide_kit::layout::usage_store(dir.path()); - let mut store = open(&path).unwrap(); - let now = instant("2026-10-01"); - store - .ingest( - "node-a", - Agent::Claude, - &source(), - &step(vec![call(1, "2026-10-01")]), - now, - &jiff::tz::TimeZone::UTC, - ) - .unwrap(); - let before = store.daily().unwrap(); - store - .connection + let v3 = V3::write( + &path, + &[("node-a", Agent::Claude, call(1, "2026-10-01"))], + &source(), + ); + rusqlite::Connection::open(&path) + .unwrap() .execute_batch("DROP TABLE price_cache; ALTER TABLE backfills DROP COLUMN limited; PRAGMA user_version=1;") .unwrap(); - drop(store); let store = open(&path).unwrap(); - assert_eq!(store.daily().unwrap(), before); + assert_eq!(store.daily().unwrap(), v3.daily); + assert!(store.converting().unwrap()); assert_eq!( store.prices().unwrap(), crate::usage_ledger::prices::Cache::default() @@ -369,7 +364,7 @@ fn lost_checkpoints_after_sixty_days_cannot_change_frozen_or_recent_totals() { assert_eq!( store .connection - .query_row("SELECT count(*) FROM events", [], |r| r.get::<_, u64>(0)) + .query_row("SELECT count(*) FROM calls", [], |r| r.get::<_, u64>(0)) .unwrap(), 1 ); @@ -440,7 +435,10 @@ fn batch_failure_rolls_back_totals_and_checkpoint_and_capacity_reports_a_limit() ); store .connection - .execute("INSERT INTO devices VALUES('node-a',?1)", [EVENT_LIMIT]) + .execute( + "INSERT INTO devices(device,calls) VALUES('node-a',?1)", + [EVENT_LIMIT], + ) .unwrap(); let outcome = store .ingest( @@ -627,7 +625,9 @@ fn a_store_from_before_hide_ai_gains_its_tables_without_a_version_change() { let path = hide_kit::layout::usage_store(dir.path()); { let connection = rusqlite::Connection::open(&path).unwrap(); - connection.execute_batch(SCHEMA).unwrap(); + connection + .execute_batch(&format!("{SCHEMA}{CALLS_SCHEMA}")) + .unwrap(); } assert_eq!(user_version(&path), VERSION); let store = open(&path).unwrap(); @@ -877,23 +877,17 @@ fn calls_of_one_time_across_the_read_limit_are_kept_by_agent_and_key() { let expected = [(1000, true), (1001, true), (1011, true), (1111, false)]; assert_eq!(read(&store), expected); - store.execute_for_test("DROP INDEX events_device_at"); + store.execute_for_test("DROP INDEX calls_node_at"); assert_eq!(read(&store), expected, "read without the index"); } -/// The projects' costs read one device's newest calls by its index rather -/// than sorting the window, sorting only calls of one time; a store from -/// before the index gains it when it opens, its version unchanged so an -/// older build still opens it. +/// The projects' costs read one node's newest calls by `calls_node_at` and +/// sort none: beside a table without rowids the index carries the primary +/// key, so time, agent and key are already in order. #[test] -fn a_store_from_before_the_cost_index_gains_it_without_a_version_change() { +fn the_projects_costs_read_calls_by_their_index_and_sort_nothing() { let dir = tempfile::tempdir().unwrap(); - let path = hide_kit::layout::usage_store(dir.path()); - open(&path) - .unwrap() - .execute_for_test("DROP INDEX events_device_at"); - let store = open(&path).unwrap(); - assert_eq!(user_version(&path), 3); + let store = open(&hide_kit::layout::usage_store(dir.path())).unwrap(); let mut query = store .connection .prepare(&format!("EXPLAIN QUERY PLAN {RECENT_CALLS}")) @@ -904,9 +898,585 @@ fn a_store_from_before_the_cost_index_gains_it_without_a_version_change() { .collect::, _>>() .unwrap(); assert!( - plan.iter().any(|step| step.contains("events_device_at")) - // Sorting the calls of one time is "FOR LAST 2 TERMS OF ORDER BY". - && !plan.iter().any(|step| step == "USE TEMP B-TREE FOR ORDER BY"), + plan.iter().any(|step| step.contains("calls_node_at")) + && !plan.iter().any(|step| step.contains("TEMP B-TREE")), "{plan:?}" ); } + +/// A history shaped like an operator's: a few hundred calls a session, a +/// worktree folder per session, two agents' model names, uuid sessions, +/// over the last forty days before `now`. +fn operator_like(count: usize, device: &str, now: u64) -> Vec<(String, Agent, Event)> { + (0..count) + .map(|n| { + let agent = if n % 3 == 0 { + Agent::Codex + } else { + Agent::Claude + }; + let session = n / 125; + let mut event = call(0, "2026-10-01"); + event.key = format!( + "{:x}", + ::digest(n.to_string()) + ); + event.at_ms = now - DAY_MS * 40 + (n as u64 * 5_417) % (DAY_MS * 40); + event.model = if agent == Agent::Codex { + "gpt-5.3-codex".into() + } else { + "claude-opus-4-6-20260115".into() + }; + event.session = format!("{:08x}-60d7-4a7c-ae5a-{:012x}", session, session * 7); + event.cwd = Some(format!( + "/Users/example/projects/herdr-ide.worktrees/fix-branch-{}", + session % 300 + )); + event.provider = None; + event.recorded_cost_micro_usd = None; + event.tokens = Tokens { + input: 3 + n as u64 % 40, + output: 40 + n as u64 % 900, + cache_read: 20_000 + n as u64 * 13 % 150_000, + cache_write: n as u64 * 7 % 3_000, + cache_write_1h: 0, + reasoning: (agent == Agent::Codex).then_some(n as u64 % 40), + }; + (device.to_owned(), agent, event) + }) + .collect() +} + +fn bytes_on_disk(path: &Path) -> u64 { + let wal = path.with_file_name(format!( + "{}-wal", + path.file_name().unwrap().to_string_lossy() + )); + std::fs::metadata(path).unwrap().len() + std::fs::metadata(wal).map_or(0, |m| m.len()) +} + +/// Opens the version 3 store at `path` and converts it to the end, then +/// compacts it as the worker does. +fn convert_all(path: &Path, open: impl Fn(&Path) -> Result) -> Store { + let mut store = open(path).unwrap(); + assert_eq!(user_version(path), VERSION); + while store.converting().unwrap() { + store.convert().unwrap(); + } + store.compact().unwrap(); + assert!(!store.compaction_due().unwrap()); + store +} + +/// What the converted `store` must answer as `v3` did: the same days' +/// totals, the same calls for the projects' costs as the worker reads them +/// at `now`, and every stored call found as already counted. +fn answers_as(store: &mut Store, v3: &V3, now: u64) { + use super::super::project_cost::{EVENT_LIMIT, since}; + assert_eq!(store.daily().unwrap(), v3.daily); + for (device, calls) in &v3.calls { + let window: Vec<_> = calls + .iter() + .filter(|(_, _, event)| event.at_ms >= since(now)) + .collect(); + let mut read = Vec::new(); + let limited = store + .recent_calls(device, since(now), EVENT_LIMIT, |agent, day, event| { + read.push((agent.to_owned(), day.to_owned(), event)); + Ok(()) + }) + .unwrap(); + assert_eq!(limited, window.len() > EVENT_LIMIT); + assert!( + read.iter().eq(window.into_iter().take(EVENT_LIMIT)), + "{device}: the calls read differ" + ); + } + for (device, agent) in v3.agents() { + let events: Vec = v3 + .stored + .iter() + .filter(|(d, a, _)| *d == device && *a == agent) + .map(|(_, _, event)| event.clone()) + .collect(); + for batch in events.chunks(BATCH_LIMIT) { + let outcome = store + .ingest( + &device, + agent, + &source(), + &step(batch.to_vec()), + now, + &jiff::tz::TimeZone::UTC, + ) + .unwrap(); + assert_eq!( + ( + outcome.repeated, + outcome.added, + outcome.changed, + outcome.updated + ), + (batch.len(), 0, 0, 0), + "{device} {agent:?}" + ); + } + } + assert_eq!(store.daily().unwrap(), v3.daily); +} + +/// with-hide/hide-private#672: a version 3 store of an operator's shape is +/// under half its size once converted and compacted, and answers as it did: +/// the days' totals, the projects' calls and which calls are already +/// counted, a Claude call's later view still merging into it. +#[test] +fn a_version_3_store_converts_to_under_half_its_size_and_answers_as_before() { + let dir = tempfile::tempdir().unwrap(); + let path = hide_kit::layout::usage_store(dir.path()); + let now = instant("2026-11-07"); + let mut calls = operator_like(12_000, "node-a", now); + calls.extend(operator_like(600, "device-b", now)); + let borrowed: Vec<_> = calls + .iter() + .map(|(device, agent, event)| (device.as_str(), *agent, event.clone())) + .collect(); + let v3 = V3::write(&path, &borrowed, &source()); + let before = bytes_on_disk(&path); + let mut store = convert_all(&path, open); + let after = bytes_on_disk(&path); + assert!(after * 2 < before, "{before} bytes became {after}"); + assert_eq!(v3.kept, kept_rows(&store.connection)); + answers_as(&mut store, &v3, now); + // A later, larger view of a stored Claude call still replaces it. + let (_, _, first) = v3 + .stored + .iter() + .find(|(device, agent, _)| device == "node-a" && *agent == Agent::Claude) + .unwrap(); + let mut later = first.clone(); + later.tokens.output += 1_000; + let outcome = store + .ingest( + "node-a", + Agent::Claude, + &source(), + &step(vec![later]), + now, + &jiff::tz::TimeZone::UTC, + ) + .unwrap(); + assert_eq!(outcome.updated, 1); +} + +/// A conversion stopped between steps goes on where it stopped after a +/// restart, and a step that fails moves nothing: the calls it read are +/// still waiting, and the next step takes them again. +#[test] +fn an_interrupted_conversion_goes_on_where_it_stopped() { + let dir = tempfile::tempdir().unwrap(); + let path = hide_kit::layout::usage_store(dir.path()); + let now = instant("2026-11-07"); + let calls = operator_like(CONVERT_BATCH * 2 + 100, "node-a", now); + let borrowed: Vec<_> = calls + .iter() + .map(|(device, agent, event)| (device.as_str(), *agent, event.clone())) + .collect(); + let v3 = V3::write(&path, &borrowed, &source()); + let count = |store: &Store, table: &str| -> usize { + store + .connection + .query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0)) + .unwrap() + }; + let mut store = open(&path).unwrap(); + assert_eq!(store.convert().unwrap(), CONVERT_BATCH); + drop(store); + let mut store = open(&path).unwrap(); + assert!(store.converting().unwrap()); + // A damaged call in the next batch fails the step as a whole. + store.execute_for_test(&format!( + "UPDATE events SET event='{{' WHERE rowid=(SELECT rowid FROM events ORDER BY rowid LIMIT 1 OFFSET {})", + CONVERT_BATCH / 2 + )); + assert_eq!(store.convert(), Err("usage_store_decode")); + assert_eq!( + (count(&store, "events"), count(&store, "calls")), + (CONVERT_BATCH + 100, CONVERT_BATCH) + ); + let (_, _, damaged) = &calls[CONVERT_BATCH + CONVERT_BATCH / 2]; + store.execute_for_test(&format!( + "UPDATE events SET event='{}' WHERE event='{{'", + encode(damaged).unwrap() + )); + while store.converting().unwrap() { + store.convert().unwrap(); + } + assert_eq!(count(&store, "calls"), calls.len()); + answers_as(&mut store, &v3, now); +} + +/// A build from before the calls format opens a converted store as its own: +/// the version is still 3 and every table it uses is there as it made it, +/// so it records Hide AI's calls, which this format did not change. Its +/// write of a native call into `events` is refused, and its ingest with it, +/// checkpoint included, so it counts no call it could not tell from one +/// already counted. Back on this build, the calls its native file gained +/// meanwhile are read from the same checkpoint and counted once, a later +/// view of a call already counted merged as ever. +#[test] +fn an_older_build_counts_no_call_into_a_converted_store_and_the_return_counts_each_once() { + let dir = tempfile::tempdir().unwrap(); + let path = hide_kit::layout::usage_store(dir.path()); + // Claude's own records carry no cost, so a later view merges. + let streamed = |key, day| Event { + recorded_cost_micro_usd: None, + ..call(key, day) + }; + let first = [streamed(1, "2026-11-01"), streamed(2, "2026-11-02")]; + V3::write( + &path, + &first.clone().map(|event| ("node-a", Agent::Claude, event)), + &source(), + ); + drop(convert_all(&path, open)); + // What a version 3 build opens and writes is there as it made it. + assert_eq!(user_version(&path), 3); + let schema = |path: &Path| -> Vec { + let db = Connection::open(path).unwrap(); + let mut query = db + .prepare( + "SELECT sql FROM sqlite_master WHERE name IN \ + ('events','events_device_at','devices','backfills','daily','daily_day',\ + 'cursors','price_cache','ai_daily','ai_daily_day','ai_state') ORDER BY name", + ) + .unwrap(); + query + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap() + }; + let made_by_version_3 = dir.path().join("v3.sqlite3"); + V3::write(&made_by_version_3, &[], &source()); + { + // What a version 3 build's own open adds. + let db = Connection::open(&made_by_version_3).unwrap(); + db.execute_batch(AI_SCHEMA).unwrap(); + } + assert_eq!(schema(&path), schema(&made_by_version_3)); + + let mut later_view = streamed(2, "2026-11-02"); + later_view.tokens.output += 50; + let new = streamed(3, "2026-11-05"); + { + let mut db = Connection::open(&path).unwrap(); + let before = kept_rows(&db); + // An older build's ingest is one transaction that writes its + // checkpoint with its calls. + let ingest = db.transaction().unwrap(); + ingest + .execute("UPDATE cursors SET checkpoint='read past'", []) + .unwrap(); + for event in [&later_view, &new] { + assert!(count_as_version_3(&ingest, "node-a", Agent::Claude, event).is_err()); + } + drop(ingest); + assert_eq!( + kept_rows(&db), + before, + "the older build's ingest rolled back whole" + ); + } + + let now = instant("2026-11-07"); + let mut store = open(&path).unwrap(); + assert!(!store.converting().unwrap()); + let mut grown = first.to_vec(); + grown.extend([later_view.clone(), new.clone()]); + let outcome = store + .ingest( + "node-a", + Agent::Claude, + &source(), + &step(grown), + now, + &jiff::tz::TimeZone::UTC, + ) + .unwrap(); + assert_eq!( + (outcome.repeated, outcome.updated, outcome.added), + (2, 1, 1) + ); + let mut alone = open(&dir.path().join("alone.sqlite3")).unwrap(); + for batch in [first.to_vec(), vec![later_view, new]] { + alone + .ingest( + "node-a", + Agent::Claude, + &source(), + &step(batch), + now, + &jiff::tz::TimeZone::UTC, + ) + .unwrap(); + } + assert_eq!(store.daily().unwrap(), alone.daily().unwrap()); +} + +/// How many calls `device` holds in `events` and in `calls`, and its count +/// in `devices`, the one count both builds read against its limit. +fn device_calls(db: &Connection, device: &str) -> (i64, i64, i64) { + db.query_row( + "SELECT (SELECT count(*) FROM events WHERE device=?1),\ + (SELECT count(*) FROM calls WHERE node=(SELECT id FROM nodes WHERE device=?1)),\ + (SELECT calls FROM devices WHERE device=?1)", + [device], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .unwrap() +} + +/// An older build that opens a store halfway through its conversion prunes +/// the calls still in `events` as it always did, taking each off the +/// device's count, which counts the device's calls in both tables: the +/// count stays the number of calls there are, never below nothing, and +/// back on this build the conversion goes on and this build's own pruning +/// takes it to nothing with the calls. +#[test] +fn an_older_build_pruning_a_halfway_conversion_keeps_one_true_count() { + let dir = tempfile::tempdir().unwrap(); + let path = hide_kit::layout::usage_store(dir.path()); + let now = instant("2026-11-07"); + let calls = operator_like(CONVERT_BATCH + 700, "node-a", now); + let borrowed: Vec<_> = calls + .iter() + .map(|(device, agent, event)| (device.as_str(), *agent, event.clone())) + .collect(); + V3::write(&path, &borrowed, &source()); + let mut store = open(&path).unwrap(); + assert_eq!(store.convert().unwrap(), CONVERT_BATCH); + drop(store); + + // Sixty days on, every call is past the older build's horizon. + let later = now + 60 * DAY_MS; + let zone = jiff::tz::TimeZone::UTC; + let db = Connection::open(&path).unwrap(); + loop { + let pruned = prune_as_version_3(&db, freeze_at(later, &zone).unwrap()); + let (events, moved, count) = device_calls(&db, "node-a"); + assert_eq!(count, events + moved, "one count of both tables"); + if pruned < 512 { + assert_eq!((events, moved), (0, CONVERT_BATCH as i64)); + break; + } + } + drop(db); + + let mut store = open(&path).unwrap(); + assert!(!store.converting().unwrap()); + while store.prune(later, &zone).unwrap() {} + assert_eq!(device_calls(&store.connection, "node-a"), (0, 0, 0)); +} + +/// The folder `HIDE_TEST_CROSS_BUILD` names: the state folder whose usage +/// store a build from before the calls format made, in a run by hand +/// beside that build's own binary. +fn cross_build_store() -> std::path::PathBuf { + let Some(dir) = std::env::var_os("HIDE_TEST_CROSS_BUILD") else { + panic!("HIDE_TEST_CROSS_BUILD names no state folder"); + }; + hide_kit::layout::usage_store(Path::new(&dir)) +} + +/// The one device a cross-build store counts calls for. +fn cross_build_device(db: &Connection) -> String { + db.query_row("SELECT device FROM devices", [], |r| r.get(0)) + .unwrap() +} + +/// Reads every native Claude file under `home` from the checkpoint `store` +/// holds for it, as the worker does, and counts what it finds. +fn read_native_files(store: &mut Store, device: &str, home: &Path, now: u64) { + let zone = jiff::tz::TimeZone::system(); + let agent = Agent::Claude; + for candidate in hide_session::usage::list(home, agent, 0).unwrap().files { + let saved = store.checkpoint(device, agent, &candidate.path).unwrap(); + if saved + .as_ref() + .is_some_and(|(stamp, checkpoint)| stamp == &candidate && checkpoint.is_finished()) + { + continue; + } + let path = hide_platform::path::from_wire(&candidate.path).unwrap(); + let mut checkpoint = saved.map(|(_, checkpoint)| checkpoint); + loop { + let step = hide_session::usage::read(home, agent, &path, checkpoint).unwrap(); + store + .ingest(device, agent, &candidate, &step, now, &zone) + .unwrap(); + if !step.has_more { + break; + } + checkpoint = Some(step.checkpoint); + } + } +} + +/// This build's part of a run by hand from a build before the calls format +/// to this one, to that one and back (`agents/runs` keeps the script; the +/// pull request shows its output): opens the store that build made in the +/// state folder `HIDE_TEST_CROSS_BUILD` names and moves +/// `HIDE_TEST_CROSS_BATCHES` steps of its calls, or all of them, before +/// that build runs on it again. +#[test] +#[ignore = "run by hand beside an older build's binary"] +fn cross_build_convert() { + let path = cross_build_store(); + let batches = std::env::var("HIDE_TEST_CROSS_BATCHES").unwrap(); + let mut store = open(&path).unwrap(); + let device = cross_build_device(&store.connection); + let before = device_calls(&store.connection, &device); + let mut steps = 0; + while store.converting().unwrap() && (batches == "all" || steps < batches.parse().unwrap()) { + store.convert().unwrap(); + steps += 1; + } + if batches == "all" { + store.compact().unwrap(); + } + let after = device_calls(&store.connection, &device); + println!("cross_build_convert: (events, calls, count) {before:?} -> {after:?}"); + assert_eq!(after.2, after.0 + after.1); + assert_eq!(after.2, before.2, "a move leaves the count alone"); +} + +/// The last part of [`cross_build_convert`]'s run, back on this build after +/// the older build ran on the store: the conversion goes on, every native +/// file under the home `HIDE_TEST_CROSS_HOME` names is read from the +/// checkpoint the store holds, and the days' totals are those of a store +/// that read the same files once with this build alone; the device's count +/// is the calls it holds, before and after. +#[test] +#[ignore = "run by hand beside an older build's binary"] +fn cross_build_return() { + let path = cross_build_store(); + let home = std::path::PathBuf::from(std::env::var_os("HIDE_TEST_CROSS_HOME").unwrap()); + let now = crate::links::now_ms(); + let mut store = open(&path).unwrap(); + let device = cross_build_device(&store.connection); + let back = device_calls(&store.connection, &device); + assert!(back.2 >= 0 && back.2 == back.0 + back.1, "{back:?}"); + while store.converting().unwrap() { + store.convert().unwrap(); + } + read_native_files(&mut store, &device, &home, now); + let dir = tempfile::tempdir().unwrap(); + let mut alone = open(&hide_kit::layout::usage_store(dir.path())).unwrap(); + read_native_files(&mut alone, &device, &home, now); + let after = device_calls(&store.connection, &device); + println!( + "cross_build_return: (events, calls, count) back {back:?}, after {after:?}, alone {:?}; {} daily rows", + device_calls(&alone.connection, &device), + alone.daily().unwrap().len() + ); + assert_eq!(after.2, after.1); + assert_eq!(store.daily().unwrap(), alone.daily().unwrap()); +} + +/// A place leaves with its last call: once a session's calls are past the +/// event horizon and pruned, its row goes too, and a session with a call +/// left keeps its row. +#[test] +fn a_place_is_pruned_with_its_last_call() { + let dir = tempfile::tempdir().unwrap(); + let mut store = open(&hide_kit::layout::usage_store(dir.path())).unwrap(); + let zone = jiff::tz::TimeZone::UTC; + let in_session = |key: u8, day: &str, session: &str| { + let mut event = call(key, day); + event.session = session.into(); + event + }; + let early = instant("2026-09-01"); + store + .ingest( + "node-a", + Agent::Claude, + &source(), + &step(vec![ + in_session(1, "2026-08-20", "gone"), + in_session(2, "2026-08-20", "kept"), + in_session(3, "2026-08-31", "kept"), + ]), + early, + &zone, + ) + .unwrap(); + store + .complete_backfill("node-a", Agent::Claude, early, &zone) + .unwrap(); + let places = |store: &Store| -> Vec { + let mut query = store + .connection + .prepare("SELECT session FROM places ORDER BY session") + .unwrap(); + query + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap() + }; + assert_eq!(places(&store), ["gone", "kept"]); + // 2026-08-20 is past the 45-day horizon on 2026-10-10, 2026-08-31 is not. + while store.prune(instant("2026-10-10"), &zone).unwrap() {} + assert_eq!(places(&store), ["kept"]); +} + +/// The operator's own store, converted from a read-only copy: run by hand +/// with `HIDE_TEST_USAGE_COPY` naming a copy of a version 3 +/// `usage.sqlite3`, on the real clock, so each step's budget is the +/// worker's (`cargo nextest run -p hide-core --run-ignored only +/// operator_copy`). The copy is copied again into a temporary folder; the +/// file named is never opened for writing. +#[test] +#[ignore = "needs a copy of an operator's version 3 usage store"] +fn operator_copy_converts_to_under_half_and_answers_as_before() { + let Some(copy) = std::env::var_os("HIDE_TEST_USAGE_COPY") else { + panic!("HIDE_TEST_USAGE_COPY names no copy"); + }; + let dir = tempfile::tempdir().unwrap(); + let path = hide_kit::layout::usage_store(dir.path()); + // Written anew rather than copied: a copy keeps a read-only copy's mode. + std::fs::write(&path, std::fs::read(©).unwrap()).unwrap(); + let v3 = V3::read(&path); + let before = bytes_on_disk(&path); + let newest = v3 + .stored + .iter() + .map(|(_, _, event)| event.at_ms) + .max() + .unwrap(); + let started = Instant::now(); + let mut steps = 0; + let mut store = Store::open(&path).unwrap(); + let opened = started.elapsed(); + let mut slowest = Duration::ZERO; + while store.converting().unwrap() { + let step = Instant::now(); + store.convert().unwrap(); + slowest = slowest.max(step.elapsed()); + steps += 1; + } + let moved = started.elapsed(); + store.compact().unwrap(); + let compacted = started.elapsed() - moved; + let after = bytes_on_disk(&path); + eprintln!( + "{} calls: {before} -> {after} bytes ({:.1}%), open {opened:?}, {steps} steps in {moved:?} \ + (slowest {slowest:?}), compaction {compacted:?}", + v3.stored.len(), + after as f64 * 100.0 / before as f64 + ); + assert!(after * 2 < before); + assert_eq!(v3.kept, kept_rows(&store.connection)); + answers_as(&mut store, &v3, newest); +} diff --git a/hide-core/src/usage_ledger/store/v3_fixture.rs b/hide-core/src/usage_ledger/store/v3_fixture.rs new file mode 100644 index 0000000000..d0e4b335c7 --- /dev/null +++ b/hide-core/src/usage_ledger/store/v3_fixture.rs @@ -0,0 +1,251 @@ +//! A version 3 store as every build before with-hide/hide-private#672 wrote +//! it, for the tests of its conversion: written from calls, or read from a +//! copy, with the answers the converted store must give again. + +use std::path::Path; + +use hide_session::Agent; +use hide_session::usage::{Candidate, Checkpoint, Event}; +use rusqlite::{Connection, OptionalExtension, params}; + +use super::{Daily, Totals, decode, encode}; +use crate::usage_ledger::local_day; + +/// The version 3 schema, as every build before with-hide/hide-private#672 +/// made it. +pub(crate) const V3_SCHEMA: &str = " +CREATE TABLE events(device TEXT NOT NULL, agent TEXT NOT NULL, key TEXT NOT NULL, + day TEXT NOT NULL, fingerprint BLOB NOT NULL, at INTEGER NOT NULL, + event TEXT NOT NULL, PRIMARY KEY(device,agent,key)); +CREATE INDEX events_at ON events(at); +CREATE INDEX events_device_at ON events(device,at); +CREATE TABLE backfills(device TEXT NOT NULL, agent TEXT NOT NULL, + completed INTEGER NOT NULL DEFAULT 0, frozen_at INTEGER NOT NULL DEFAULT 0, + limited INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(device,agent)); +CREATE TABLE daily(device TEXT NOT NULL, agent TEXT NOT NULL, day TEXT NOT NULL, + model TEXT NOT NULL, totals TEXT NOT NULL, PRIMARY KEY(device,agent,day,model)); +CREATE INDEX daily_day ON daily(day); +CREATE TABLE cursors(device TEXT NOT NULL, agent TEXT NOT NULL, path TEXT NOT NULL, + stamp TEXT NOT NULL, checkpoint TEXT NOT NULL, PRIMARY KEY(device,agent,path)); +CREATE TABLE devices(device TEXT PRIMARY KEY, calls INTEGER NOT NULL DEFAULT 0); +CREATE TABLE price_cache(slot INTEGER PRIMARY KEY CHECK(slot=1), value TEXT NOT NULL); +PRAGMA user_version=3; +"; + +/// What a version 3 store holds, read before it is converted: the answers +/// the converted store must give again. +pub(crate) struct V3 { + pub(crate) daily: Vec, + /// Each node's calls as `recent_calls` hands them on: agent, day and + /// event, newest first, then by agent and key. + pub(crate) calls: std::collections::BTreeMap>, + /// Every call with its node and agent, in the order it was stored. + pub(crate) stored: Vec<(String, Agent, Event)>, + /// The tables a conversion leaves alone, row by row. + pub(crate) kept: Vec, +} + +impl V3 { + /// Writes `calls` as a build before the calls format stored them: the whole + /// event as JSON beside its key, its day's totals, the node's count, a + /// completed backfill and a checkpoint at the start of `file`. + pub(crate) fn write(path: &Path, calls: &[(&str, Agent, Event)], file: &Candidate) -> Self { + let db = Connection::open(path).unwrap(); + db.execute_batch(&format!("BEGIN;{V3_SCHEMA}")).unwrap(); + for (device, agent, event) in calls { + count_as_version_3(&db, device, *agent, event).unwrap(); + let agent = agent.as_str(); + db.execute( + "INSERT OR IGNORE INTO backfills(device,agent,completed) VALUES(?1,?2,1)", + params![device, agent], + ) + .unwrap(); + db.execute( + "INSERT OR IGNORE INTO cursors VALUES(?1,?2,?3,?4,?5)", + params![ + device, + agent, + file.path, + encode(file).unwrap(), + encode(&Checkpoint::default()).unwrap() + ], + ) + .unwrap(); + } + db.execute_batch("COMMIT;").unwrap(); + drop(db); + Self::read(path) + } + + /// The answers a version 3 store at `path` gives, read without + /// changing it. + pub(crate) fn read(path: &Path) -> Self { + let db = + Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap(); + assert_eq!( + db.pragma_query_value(None, "user_version", |r| r.get::<_, i64>(0)) + .unwrap(), + 3 + ); + let daily = db + .prepare("SELECT device,agent,day,model,totals FROM daily ORDER BY day,agent,model") + .unwrap() + .query_map([], |r| { + Ok(Daily { + device: r.get(0)?, + agent: r.get(1)?, + day: r.get(2)?, + model: r.get(3)?, + totals: decode(&r.get::<_, String>(4)?).unwrap(), + }) + }) + .unwrap() + .collect::, _>>() + .unwrap(); + let mut calls = std::collections::BTreeMap::>::new(); + let mut stored = Vec::new(); + let mut query = db + .prepare("SELECT device,agent,day,event,key FROM events ORDER BY rowid") + .unwrap(); + let mut rows = query.query([]).unwrap(); + while let Some(row) = rows.next().unwrap() { + let device: String = row.get(0).unwrap(); + let agent: String = row.get(1).unwrap(); + let mut event: Event = decode(&row.get::<_, String>(3).unwrap()).unwrap(); + event.key = row.get(4).unwrap(); + stored.push(( + device.clone(), + Agent::supported() + .find(|known| known.as_str() == agent) + .unwrap(), + event.clone(), + )); + calls + .entry(device) + .or_default() + .push((agent, row.get(2).unwrap(), event)); + } + for list in calls.values_mut() { + list.sort_by(|a, b| (b.2.at_ms, &a.0, &a.2.key).cmp(&(a.2.at_ms, &b.0, &b.2.key))); + } + Self { + daily, + calls, + stored, + kept: kept_rows(&db), + } + } + + pub(crate) fn agents(&self) -> Vec<(String, Agent)> { + let mut agents: Vec<(String, Agent)> = Vec::new(); + for (device, agent, _) in &self.stored { + if !agents.iter().any(|(d, a)| d == device && a == agent) { + agents.push((device.clone(), *agent)); + } + } + agents + } +} + +/// Counts `event` as a version 3 build counts a call it finds no row of in +/// `events`, in its order: its day's totals, then the whole event as JSON +/// beside its key, then the device's count. What a build before +/// with-hide/hide-private#672 asks of a store this build converted, which +/// refuses the first write. +pub(crate) fn count_as_version_3( + db: &Connection, + device: &str, + agent: Agent, + event: &Event, +) -> rusqlite::Result<()> { + let agent = agent.as_str(); + let day = local_day(event.at_ms, &jiff::tz::TimeZone::UTC).unwrap(); + let json = encode(event).unwrap(); + let fingerprint = sha2::Digest::finalize(sha2::Digest::chain_update( + ::new(), + json.as_bytes(), + )) + .to_vec(); + let totals: Option = db + .query_row( + "SELECT totals FROM daily WHERE device=?1 AND agent=?2 AND day=?3 AND model=?4", + params![device, agent, day, event.model], + |r| r.get(0), + ) + .optional()?; + let mut totals: Totals = totals.map(|t| decode(&t).unwrap()).unwrap_or_default(); + totals.add(event).unwrap(); + db.execute( + "INSERT INTO daily VALUES(?1,?2,?3,?4,?5) ON CONFLICT(device,agent,day,model) \ + DO UPDATE SET totals=excluded.totals", + params![device, agent, day, event.model, encode(&totals).unwrap()], + )?; + db.execute( + "INSERT INTO events VALUES(?1,?2,?3,?4,?5,?6,?7)", + params![ + device, + agent, + event.key, + day, + fingerprint, + event.at_ms, + json + ], + )?; + db.execute( + "INSERT INTO devices VALUES(?1,1) ON CONFLICT(device) DO UPDATE SET calls=calls+1", + [device], + )?; + Ok(()) +} + +/// Prunes as a version 3 build's maintenance turn prunes calls, in its +/// order: each completed backfill's horizon moves up to `frozen`, then at +/// most 512 calls before it leave `events`, each taken off its device's +/// count. Answers how many left. +pub(crate) fn prune_as_version_3(db: &Connection, frozen: u64) -> usize { + db.execute( + "UPDATE backfills SET frozen_at=max(frozen_at,?1) WHERE completed=1", + [frozen], + ) + .unwrap(); + let mut query = db + .prepare( + "SELECT e.rowid,e.device FROM events e WHERE e.at = query + .query_map([frozen], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + for (id, device) in &expired { + db.execute("DELETE FROM events WHERE rowid=?1", [id]) + .unwrap(); + db.execute("UPDATE devices SET calls=calls-1 WHERE device=?1", [device]) + .unwrap(); + } + expired.len() +} + +/// Every row of the tables a conversion must leave as they were. +pub(crate) fn kept_rows(db: &Connection) -> Vec { + let mut rows = Vec::new(); + for table in ["backfills", "daily", "cursors", "devices", "price_cache"] { + let mut query = db + .prepare(&format!("SELECT * FROM {table} ORDER BY 1,2,3")) + .or_else(|_| db.prepare(&format!("SELECT * FROM {table}"))) + .unwrap(); + let width = query.column_count(); + let mut found = query.query([]).unwrap(); + while let Some(row) = found.next().unwrap() { + let cells = (0..width) + .map(|at| format!("{:?}", row.get_ref(at).unwrap())) + .collect::>(); + rows.push(format!("{table}:{}", cells.join("|"))); + } + } + rows +} diff --git a/hide-core/src/usage_ledger/worker.rs b/hide-core/src/usage_ledger/worker.rs index 1363bf7f1d..9c993b9cc2 100644 --- a/hide-core/src/usage_ledger/worker.rs +++ b/hide-core/src/usage_ledger/worker.rs @@ -238,6 +238,14 @@ struct Engine { ai_limited: bool, ai_dirty: bool, failure: Option<&'static str>, + /// Version 3 calls still wait to be moved (`Store::convert`): until they + /// are, no call is read, counted or pruned. + converting: bool, + /// The calls this process moved, logged when the last batch moved. + converted: u64, + convert_retry: Option, + /// Compacting is looked at once per open and once after a conversion. + compacting: bool, pruned: Instant, pruning: bool, prune_retry: Option, @@ -286,6 +294,8 @@ impl Engine { ai: Arc, ) -> Result { let store = Store::open(path)?; + let converting = store.converting()?; + let compacting = !converting && store.compaction_due()?; let agents = Agent::supported() .filter(|agent| *agent != Agent::Cursor) .map(|agent| { @@ -337,6 +347,10 @@ impl Engine { ai_limited, ai_dirty: ai_unread, failure: None, + converting, + converted: 0, + convert_retry: None, + compacting, pruned: Instant::now(), pruning: true, prune_retry: None, @@ -402,6 +416,25 @@ impl Engine { /// One node read and one atomic store step per turn, followed by a rest. /// Round-robin selection prevents a large agent history starving another. fn step(&mut self, own: &dyn NodeLink, activity: Activity) { + if self.converting { + self.convert_step(); + return; + } + if self.compacting { + self.compacting = false; + // The operator cannot act on a store left larger than it could + // be: its failure goes to the log, and the next open looks again. + match self + .store + .compaction_due() + .and_then(|due| due.then(|| self.store.compact()).transpose()) + { + Ok(Some(())) => diagnostic("usage_store_compacted", None, 0), + Ok(None) => {} + Err(code) => diagnostic(code, None, 0), + } + return; + } let now = crate::links::now_ms(); let zone = jiff::tz::TimeZone::system(); if (self.pruning || self.pruned.elapsed() >= Duration::from_secs(30 * 60)) @@ -580,6 +613,37 @@ impl Engine { } } + /// One batch of a version 3 store's calls moved. A failed batch moved + /// nothing and is tried again after `RETRY`. + fn convert_step(&mut self) { + if self.convert_retry.is_some_and(|at| at.elapsed() < RETRY) { + return; + } + match self + .store + .convert() + .and_then(|moved| Ok((moved, self.store.converting()?))) + { + Ok((moved, left)) => { + self.convert_retry = None; + self.converted += moved as u64; + if !left { + self.converting = false; + // The moved calls left their old pages free. + self.compacting = true; + self.costs.dirty = true; + // A failure a batch reported clears with the next read. + self.dirty = true; + diagnostic("usage_store_converted", None, self.converted); + } + } + Err(code) => { + self.convert_retry = Some(Instant::now()); + self.failed(code); + } + } + } + fn finish(&mut self, index: usize, now: u64, zone: &jiff::tz::TimeZone) { let work = &mut self.agents[index]; if work.progress.reading && !work.failed { @@ -665,6 +729,11 @@ impl Engine { /// build keeps the last costs, stays due and is tried again after the /// same wait, logged once per cause; the frame says it failed (B33). fn project_costs(&mut self, projects: &Arc>) -> ProjectCosts { + // Calls still being moved would read as missing; the costs stay + // pending until the conversion ends. + if self.converting { + return self.costs.published(); + } let now = crate::links::now_ms(); let zone = jiff::tz::TimeZone::system(); let Ok(today) = super::local_day(now, &zone) else { diff --git a/hide-core/src/usage_ledger/worker/tests.rs b/hide-core/src/usage_ledger/worker/tests.rs index ce1a3e9550..4b401dcb8f 100644 --- a/hide-core/src/usage_ledger/worker/tests.rs +++ b/hide-core/src/usage_ledger/worker/tests.rs @@ -587,7 +587,7 @@ fn a_failed_cost_build_keeps_the_last_costs_and_is_tried_again() { let past = Instant::now() - COST_REBUILD; engine .store - .execute_for_test("ALTER TABLE events RENAME TO events_gone"); + .execute_for_test("ALTER TABLE calls RENAME TO calls_gone"); engine.costs.dirty = true; engine.costs.built = Some(past); let failed = engine.report(true, &projects).projects; @@ -601,9 +601,72 @@ fn a_failed_cost_build_keeps_the_last_costs_and_is_tried_again() { engine .store - .execute_for_test("ALTER TABLE events_gone RENAME TO events"); + .execute_for_test("ALTER TABLE calls_gone RENAME TO calls"); engine.costs.built = Some(past); let again = engine.report(true, &projects).projects; assert!(!again.failed); assert_eq!(again.built.unwrap().len(), 1); } + +/// with-hide/hide-private#672: an engine opened on a version 3 store moves +/// its calls before it reads, counts or prunes any, keeping the projects' +/// costs pending meanwhile, then compacts the file once and builds them +/// from the moved calls. +#[test] +fn a_version_3_store_is_converted_before_anything_reads_its_calls() { + use crate::usage_ledger::store::v3_fixture::V3; + let home = tempfile::tempdir().unwrap(); + let path = home.path().join("ledger.sqlite3"); + let event = hide_session::usage::Event { + key: "ab".repeat(32), + at_ms: crate::links::now_ms() - 60_000, + model: "fixture-model".into(), + tokens: hide_session::usage::Tokens { + input: 10, + output: 20, + cache_read: 900, + cache_write: 30, + cache_write_1h: 0, + reasoning: None, + }, + recorded_cost_micro_usd: Some(4_000), + session: "converted".into(), + cwd: Some("/work/hide".into()), + provider: None, + incomplete: false, + }; + let file = Candidate { + path: "/native/calls.jsonl".into(), + size: 1, + modified_ms: 1, + }; + let v3 = V3::write(&path, &[("physical-device", Agent::Claude, event)], &file); + let node = OwnNode::new(home.path()); + let mut engine = Engine::open(&path, "physical-device".into(), AiUsageQueue::new()).unwrap(); + let projects = Arc::new(vec![ProjectRoots { + workspace_id: "hide".into(), + roots: vec!["/work/hide".into()], + }]); + assert!(engine.converting); + assert_eq!( + engine.report(true, &projects).projects, + ProjectCosts::default(), + "pending while calls are moved" + ); + let visible = Activity { + visible: true, + open: true, + }; + engine.step(&node, visible); + assert_eq!(node.calls.load(Ordering::SeqCst), 0, "nothing read yet"); + assert!(!engine.converting && engine.compacting); + engine.step(&node, visible); + assert!(!engine.compacting); + let report = engine.report(true, &projects); + assert_eq!(*engine.daily, v3.daily); + let built = report.projects.built.unwrap(); + assert_eq!( + (built[0].workspace_id.as_str(), built[0].tokens), + ("hide", 60) + ); +}