Repository navigation
feat(savings): move OpenHuman accounting behind module bus contract #66
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
10 commits
Select commit
Hold shift + click to select a range
ff735ce
feat(bus): add savings tracking methods to the bus contract
senamakel ff38d93
feat(savings): expose savings ledger through module service
senamakel a819e1f
test(savings): cover savings recording and persistence in the loaded …
senamakel 1425e3d
feat(module): expose savings ledger bus members
senamakel 4eac0c4
chore(deps): add tempfile to tinyjuice-module
senamakel 2801ff3
test(savings): cover loading a pre-migration openhuman snapshot
senamakel f6ffeb2
test(tinyjuice-bus): cover rejection of contract 2.0
senamakel b980cbe
test(tinyjuice-bus): reformat version compatibility assertion
senamakel 1bb888b
test(savings): cover overflow handling in ledger aggregates
senamakel 66614d3
fix(savings): saturate ledger totals instead of wrapping
senamakel 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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 |
|---|---|---|
|
|
@@ -13,6 +13,7 @@ | |
|
|
||
| pub mod names; | ||
| pub mod repl; | ||
| pub mod savings; | ||
| pub mod summary; | ||
| pub mod tools; | ||
| pub mod types; | ||
|
|
||
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,48 @@ | ||
| //! Persisted savings totals and requests shared with the compression module. | ||
|
|
||
| use serde::{Deserialize, Serialize}; | ||
| use std::collections::HashMap; | ||
|
|
||
| /// Per-key (model / compressor) rolled-up savings. | ||
| #[derive(Debug, Clone, Default, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct SavingsBucket { | ||
| /// Number of shrinking compactions; saturates at `u64::MAX`. | ||
| pub events: u64, | ||
| /// Sum of estimated tokens before compaction. | ||
| pub original_tokens: u64, | ||
| /// Sum of estimated tokens after compaction. | ||
| pub compacted_tokens: u64, | ||
| /// Sum of positive pre/post token differences. | ||
| pub tokens_saved: u64, | ||
| /// Estimated dropped-input cost from host prices; saturates at `f64::MAX`. | ||
| pub cost_saved_usd: f64, | ||
| } | ||
|
|
||
| /// The full savings snapshot returned to callers / the dashboard. | ||
| #[derive(Debug, Clone, Default, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct SavingsAggregate { | ||
| /// Overall totals across every compaction. | ||
| pub total: SavingsBucket, | ||
| /// Breakdown by the model the savings were attributed to. | ||
| pub by_model: HashMap<String, SavingsBucket>, | ||
| /// Breakdown by which compressor produced the saving. | ||
| pub by_compressor: HashMap<String, SavingsBucket>, | ||
| } | ||
|
|
||
| /// One compaction attributed to the model that would consume its output. | ||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct RecordSavingsRequest { | ||
| /// Model identifier used for the dashboard breakdown and host price lookup. | ||
| pub model: String, | ||
| /// Compressor identifier used for the dashboard breakdown. | ||
| pub compressor: String, | ||
| /// Estimated input tokens before compaction. | ||
| pub original_tokens: u64, | ||
| /// Estimated input tokens after compaction. | ||
| pub compacted_tokens: u64, | ||
| /// Host-resolved price per million input tokens; absent means unpriced. | ||
| pub input_per_mtok_usd: Option<f64>, | ||
| } |
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
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,137 @@ | ||
| //! Model-attributed savings aggregation and best-effort snapshot persistence. | ||
|
|
||
| use std::path::{Path, PathBuf}; | ||
| use std::sync::Mutex; | ||
|
|
||
| pub use tinyjuice_bus::savings::{RecordSavingsRequest, SavingsAggregate, SavingsBucket}; | ||
|
|
||
| #[derive(Default)] | ||
| struct State { | ||
| aggregate: SavingsAggregate, | ||
| snapshot_path: Option<PathBuf>, | ||
| } | ||
|
|
||
| /// A thread-safe ledger scoped to its caller, without a host pricing catalog. | ||
| /// | ||
| /// Counts are estimates supplied by the compressor. Monetary savings use only | ||
| /// the host-provided input rate, with unpriced models reporting zero dollars. | ||
| #[derive(Default)] | ||
| pub struct SavingsLedger { | ||
| state: Mutex<State>, | ||
| } | ||
|
|
||
| impl SavingsLedger { | ||
| /// Creates an empty in-memory ledger. | ||
| #[must_use] | ||
| pub fn new() -> Self { | ||
| Self::default() | ||
| } | ||
|
|
||
| /// Selects a snapshot file and loads it once per path. | ||
| /// | ||
| /// Repeated configuration of the same path does not reload stale disk | ||
| /// state. Missing or malformed snapshots leave the current totals intact, | ||
| /// matching the original host ledger. I/O failures are best-effort. | ||
| pub fn configure(&self, path: &Path) { | ||
| let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); | ||
| if state.snapshot_path.as_deref() == Some(path) { | ||
| return; | ||
| } | ||
| let loaded = std::fs::read_to_string(path) | ||
| .ok() | ||
| .and_then(|text| serde_json::from_str(&text).ok()); | ||
| state.snapshot_path = Some(path.to_path_buf()); | ||
| if let Some(aggregate) = loaded { | ||
| state.aggregate = aggregate; | ||
| } | ||
| } | ||
|
|
||
| /// Records a strictly smaller compaction and snapshots its totals. | ||
| /// | ||
| /// Equal or expanded output is a no-op. Negative or non-finite input | ||
| /// prices and overflowed per-event costs are unpriced. Bucket totals | ||
| /// saturate at their largest finite representation rather than wrapping. | ||
| pub fn record(&self, request: &RecordSavingsRequest) { | ||
| if request.original_tokens <= request.compacted_tokens { | ||
| return; | ||
| } | ||
| let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); | ||
| let cost = request | ||
| .input_per_mtok_usd | ||
| .filter(|price| price.is_finite() && *price >= 0.0) | ||
| .map_or(0.0, |price| { | ||
| (request.original_tokens - request.compacted_tokens) as f64 / 1_000_000.0 * price | ||
| }); | ||
| let cost = if cost.is_finite() { cost } else { 0.0 }; | ||
| let aggregate = &mut state.aggregate; | ||
| add(&mut aggregate.total, request, cost); | ||
| add( | ||
| aggregate.by_model.entry(request.model.clone()).or_default(), | ||
| request, | ||
| cost, | ||
| ); | ||
| add( | ||
| aggregate | ||
| .by_compressor | ||
| .entry(request.compressor.clone()) | ||
| .or_default(), | ||
| request, | ||
| cost, | ||
| ); | ||
| persist(&state); | ||
| } | ||
|
|
||
| /// Returns a consistent copy of all current totals. | ||
| #[must_use] | ||
| pub fn stats(&self) -> SavingsAggregate { | ||
| self.state | ||
| .lock() | ||
| .unwrap_or_else(|p| p.into_inner()) | ||
| .aggregate | ||
| .clone() | ||
| } | ||
|
|
||
| /// Clears totals and writes the empty persisted snapshot. | ||
| pub fn reset(&self) { | ||
| let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); | ||
| state.aggregate = SavingsAggregate::default(); | ||
| persist(&state); | ||
| } | ||
| } | ||
|
|
||
| /// Accumulate one event without wrapping persisted totals at their limits. | ||
| fn add(bucket: &mut SavingsBucket, request: &RecordSavingsRequest, cost: f64) { | ||
| bucket.events = bucket.events.saturating_add(1); | ||
| bucket.original_tokens = bucket | ||
| .original_tokens | ||
| .saturating_add(request.original_tokens); | ||
| bucket.compacted_tokens = bucket | ||
| .compacted_tokens | ||
| .saturating_add(request.compacted_tokens); | ||
| bucket.tokens_saved = bucket | ||
| .tokens_saved | ||
| .saturating_add(request.original_tokens - request.compacted_tokens); | ||
| bucket.cost_saved_usd = (bucket.cost_saved_usd + cost).min(f64::MAX); | ||
| } | ||
|
senamakel marked this conversation as resolved.
|
||
|
|
||
| /// Write the snapshot best-effort, retaining the former host I/O behavior. | ||
| fn persist(state: &State) { | ||
| let Some(path) = state.snapshot_path.as_ref() else { | ||
| return; | ||
| }; | ||
| if let Some(parent) = path.parent() { | ||
| let _ = std::fs::create_dir_all(parent); | ||
| } | ||
| match serde_json::to_string(&state.aggregate) { | ||
| Ok(json) => { | ||
| if let Err(error) = std::fs::write(path, json) { | ||
| log::debug!("[tokenjuice][savings] snapshot write failed: {error}"); | ||
| } | ||
| } | ||
| Err(error) => log::debug!("[tokenjuice][savings] snapshot serialize failed: {error}"), | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "ledger_tests.rs"] | ||
| mod tests; | ||
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.