Module: LlmCostTracker::Ledger::Rollups
- Defined in:
- lib/llm_cost_tracker/ledger/rollups.rb
Class Method Summary collapse
- .cache_active? ⇒ Boolean
- .decrement!(records) ⇒ Object
- .increment!(events) ⇒ Object
- .increment_safely!(events) ⇒ Object
- .rebuild! ⇒ Object
- .rolled_back?(error) ⇒ Boolean
Class Method Details
.cache_active? ⇒ Boolean
11 12 13 14 15 16 17 |
# File 'lib/llm_cost_tracker/ledger/rollups.rb', line 11 def cache_active? return false unless LlmCostTracker.configuration.budgets.totals_source == :cache return true if LlmCostTracker::CallRollup.table_exists? warn_missing_table false end |
.decrement!(records) ⇒ Object
60 61 62 63 64 65 66 67 |
# File 'lib/llm_cost_tracker/ledger/rollups.rb', line 60 def decrement!(records) return unless cache_active? buckets = bucket_totals(records) return if buckets.empty? LlmCostTracker::CallRollup.decrement(buckets) end |
.increment!(events) ⇒ Object
19 20 21 22 23 24 25 26 |
# File 'lib/llm_cost_tracker/ledger/rollups.rb', line 19 def increment!(events) return unless cache_active? events = Array(events).select(&:total_cost) return if events.empty? LlmCostTracker::CallRollup.increment_all(period_rows_for_events(events)) end |
.increment_safely!(events) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/llm_cost_tracker/ledger/rollups.rb', line 35 def increment_safely!(events) attempt = 0 begin attempt += 1 increment!(events) rescue StandardError => e raise if LlmCostTracker::Call.connection.open_transactions.positive? if attempt < ROLLUP_INCREMENT_ATTEMPTS && rolled_back?(e) sleep(ROLLUP_INCREMENT_BASE_DELAY_SECONDS * (2**(attempt - 1))) retry end LlmCostTracker::Logging.warn( "Rollup increment failed for #{events.size} events after #{attempt} attempt(s): " \ "#{e.class}: #{e.}. Budget reads fall back to the calls ledger; " \ "run bin/rails llm_cost_tracker:rebuild_rollups to resync the cache." ) end end |
.rebuild! ⇒ Object
69 70 71 72 73 74 75 76 77 78 |
# File 'lib/llm_cost_tracker/ledger/rollups.rb', line 69 def rebuild! accumulated = accumulate_priced_calls LlmCostTracker::CallRollup.transaction do LlmCostTracker::CallRollup.delete_all rows_from_buckets(accumulated).each_slice(REBUILD_INSERT_SLICE) do |rows| LlmCostTracker::CallRollup.increment_all(rows) end end accumulated.size end |
.rolled_back?(error) ⇒ Boolean
56 57 58 |
# File 'lib/llm_cost_tracker/ledger/rollups.rb', line 56 def rolled_back?(error) error.is_a?(ActiveRecord::Deadlocked) || error.is_a?(ActiveRecord::LockWaitTimeout) end |