Repository navigation
feat(agents): reuse daily statistics for usage overviews #251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
513703f
feat(agents): reuse daily statistics for usage overviews
WhiteZeek e4f4bf0
docs(agents): link the overview contract to its pull request
WhiteZeek 57bff81
Merge remote-tracking branch 'origin/main' into feat/2594-usage-rollups
WhiteZeek 0c390b3
Recover exact usage overviews when daily cache data is unavailable
WhiteZeek 6abef77
Merge remote-tracking branch 'origin/main' into feat/2594-usage-rollups
WhiteZeek 5a88ef8
Reserve the session writer before reading records for deletion
WhiteZeek 2f236ab
Merge remote-tracking branch 'origin/main' into feat/2594-usage-rollups
WhiteZeek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| //! Local synthetic baseline for record ingestion, three exact scans and a cached overview. | ||
| //! Run with `cargo bench -p lithe-agent-sessions --bench daily_overview`. | ||
|
|
||
| use lithe_agent_sessions::pricing::PriceTable; | ||
| use lithe_agent_sessions::stats::{CallSelector, GroupBy, OverviewQuery, Summarizer}; | ||
| use lithe_agent_sessions::{database_file_name, CallFilter, SessionStore}; | ||
| use rusqlite::{params, Connection}; | ||
| use std::{fs, hint::black_box, time::Instant}; | ||
|
|
||
| const DAY: i64 = 86_400_000; | ||
|
|
||
| fn measure<T>(name: &str, work: impl FnOnce() -> T) -> T { | ||
| let start = Instant::now(); | ||
| let result = work(); | ||
| println!("{name}: {:.2} ms", start.elapsed().as_secs_f64() * 1000.); | ||
| result | ||
| } | ||
|
|
||
| fn run(days: i64) { | ||
| let root = | ||
| std::env::temp_dir().join(format!("lithe-usage-bench-{}-{days}", std::process::id())); | ||
| fs::create_dir(&root).expect("create a fresh benchmark directory"); | ||
| let store = SessionStore::open(&root).unwrap(); | ||
| let database = root.join(database_file_name()); | ||
| let db = Connection::open(&database).unwrap(); | ||
| let count = days * 1000; | ||
| db.execute("INSERT INTO files(id,agent,path,cursor_offset,fingerprint,generation) VALUES(1,'bench','sample',0,x'',1)", []).unwrap(); | ||
| measure("ingest", || { | ||
| db.execute( | ||
| "WITH RECURSIVE n(i) AS (VALUES(0) UNION ALL SELECT i+1 FROM n WHERE i+1 < ?1) | ||
| INSERT INTO calls(file_id,call_key,session_id,started_at_ms,model,input_tokens,output_tokens, | ||
| cache_read_tokens,first_token_ms,duration_ms,compaction,range_start,range_end) | ||
| SELECT 1,printf('c%d',i),'s',(i/1000)*86400000+i%1000,printf('m%d',i%4),500,100+i%809, | ||
| 20,100+i%17,1200+i%391,0,i,i+1 FROM n", [count]).unwrap() | ||
| }); | ||
| let filter = CallFilter { | ||
| agents: vec!["bench".into()], | ||
| ..CallFilter::default() | ||
| }; | ||
| let calendar = OverviewQuery { | ||
| today_ms: days * DAY, | ||
| initial_offset: 0, | ||
| offsets: vec![], | ||
| }; | ||
| let day = GroupBy::Day { | ||
| utc_offset_seconds: 0, | ||
| }; | ||
| let overview = |selector: &CallSelector, prices: Option<&PriceTable>| { | ||
| store | ||
| .usage_overview(&filter, selector, prices, day, GroupBy::Model, &calendar) | ||
| .unwrap() | ||
| }; | ||
| let all = CallSelector::default(); | ||
| let legacy = measure("three detail scans", || { | ||
| [GroupBy::All, GroupBy::Model, day].map(|group| { | ||
| let mut sums = Summarizer::new(group, None).detailed(); | ||
| if group == day { | ||
| sums = sums.split_by(GroupBy::Model); | ||
| } | ||
| store | ||
| .for_each_call(&filter, |entry| { | ||
| sums.add(&entry); | ||
| Ok(()) | ||
| }) | ||
| .unwrap(); | ||
| sums.finish() | ||
| }) | ||
| }); | ||
| let size = || { | ||
| db.query_row( | ||
| "SELECT page_count * page_size FROM pragma_page_count, pragma_page_size", | ||
| [], | ||
| |r| r.get::<_, i64>(0), | ||
| ) | ||
| .unwrap() | ||
| }; | ||
| let before = size(); | ||
| let cold = measure("cold overview", || overview(&all, None)); | ||
| assert_eq!(cold.summaries, legacy[0]); | ||
| assert_eq!(cold.groups, legacy[1]); | ||
| assert_eq!(cold.series, legacy[2]); | ||
| println!( | ||
| "{count} calls over {days} days, database {before} -> {} bytes", | ||
| size() | ||
| ); | ||
| for _ in 0..3 { | ||
| let warm = measure("warm overview", || overview(&all, None)); | ||
| assert_eq!(black_box(warm.summaries), legacy[0]); | ||
| } | ||
| let today = OverviewQuery { | ||
| today_ms: (days - 1) * DAY, | ||
| initial_offset: 0, | ||
| offsets: Vec::new(), | ||
| }; | ||
| let live = measure("warm overview with 1000 calls today", || { | ||
| store | ||
| .usage_overview(&filter, &all, None, day, GroupBy::Model, &today) | ||
| .unwrap() | ||
| }); | ||
| assert_eq!(live.summaries, legacy[0]); | ||
| measure("late insert", || { | ||
| db.execute( | ||
| "INSERT INTO calls(file_id,call_key,session_id,started_at_ms,model,output_tokens,compaction,range_start,range_end) | ||
| VALUES(1,'late','s',?1,'m0',100,0,0,1)", params![DAY+7]).unwrap() | ||
| }); | ||
| let changed = measure("refresh after late insert", || overview(&all, None)); | ||
| assert_eq!(changed.summaries[0].calls, count as u64 + 1); | ||
| let prices = | ||
| PriceTable::from_models_dev(br#"{"p":{"models":{"m0":{"cost":{"input":1,"output":2}}}}}"#) | ||
| .unwrap(); | ||
| measure("new price table", || overview(&all, Some(&prices))); | ||
| measure("text search", || { | ||
| overview(&CallSelector::default().with_search("m1"), Some(&prices)) | ||
| }); | ||
| drop(db); | ||
| drop(store); | ||
| fs::remove_file(database).unwrap(); | ||
| fs::remove_dir(root).unwrap(); | ||
| } | ||
|
|
||
| fn main() { | ||
| // Cargo also runs custom harnesses under test --all-targets. | ||
| if !std::env::args_os().any(|arg| arg == "--bench") { | ||
| return; | ||
| } | ||
| for days in [175, 350] { | ||
| run(days); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.