A platform for community discussion. Free, open, simple.
DEV: Move AI credits daily usage to it's own table (#36369)
Keegan George150c51aedc95
diff --git a/plugins/discourse-ai/app/models/llm_credit_allocation.rb b/plugins/discourse-ai/app/models/llm_credit_allocation.rbindex 13b501dc992..884f8af3a37 100644--- a/plugins/discourse-ai/app/models/llm_credit_allocation.rb+++ b/plugins/discourse-ai/app/models/llm_credit_allocation.rb@@ -12,9 +12,16 @@ class LlmCreditAllocation < ActiveRecord::Baseendend+ # DEPRECATED: Only used for JSONB daily_usage cleanup during migration period+ # TODO: Remove this constant once daily_usage column is droppedDAILY_USAGE_RETENTION_DAYS = 90belongs_to :llm_model+ has_many :daily_usages,+ class_name: "LlmCreditDailyUsage",+ foreign_key: :llm_model_id,+ primary_key: :llm_model_id,+ dependent: :destroy# TODO: Remove once both column-dropping migrations have been promoted to pre-deploy:# - 20251105174003 (drops monthly_used, last_reset_at)@@ -31,17 +38,42 @@ class LlmCreditAllocation < ActiveRecord::Baseless_than_or_equal_to: 100,}+ # DEPRECATED: Used for JSONB daily_usage column which is being phased out+ # TODO: Remove once daily_usage column is droppeddef current_day_keyTime.current.utc.strftime("%Y-%m-%d")enddef daily_used- daily_usage[current_day_key].to_i+ # Primary: Use llm_credit_daily_usages table+ # Check if association is preloaded to avoid N+1 queries+ if association(:daily_usages).loaded?+ usage_record = daily_usages.find { |u| u.usage_date == Date.current }+ return usage_record.credits_used if usage_record+ else+ usage_record =+ LlmCreditDailyUsage.find_by(llm_model_id: llm_model_id, usage_date: Date.current)+ return usage_record.credits_used if usage_record+ end++ # DEPRECATED: Fallback to JSONB daily_usage column for backwards compatibility+ # TODO: Remove this fallback once daily_usage column is dropped and added to ignored_columns+ return daily_usage[current_day_key].to_i if respond_to?(:daily_usage) && daily_usage.present?++ 0enddef daily_used=(value)- day_key = current_day_key- self.daily_usage = (daily_usage || {}).merge(day_key => value.to_i)+ usage_record =+ LlmCreditDailyUsage.find_or_create_by!(llm_model_id: llm_model_id, usage_date: Date.current)+ usage_record.update!(credits_used: value.to_i)++ # DEPRECATED: Dual-write to JSONB daily_usage column during migration period+ # TODO: Remove this dual-write once daily_usage column is dropped+ if respond_to?(:daily_usage=)+ day_key = current_day_key+ self.daily_usage = (daily_usage || {}).merge(day_key => value.to_i)+ endenddef credits_remaining@@ -79,12 +111,22 @@ class LlmCreditAllocation < ActiveRecord::Baseenddef deduct_credits!(credits)- with_lock do- reload- day_key = current_day_key- self.daily_usage = daily_usage.merge(day_key => daily_used + credits)- cleanup_old_days!- save!+ LlmCreditDailyUsage.increment_usage!(llm_model, credits)++ # DEPRECATED: Dual-write to JSONB daily_usage column during migration period+ # TODO: Remove this entire block once daily_usage column is dropped+ if respond_to?(:daily_usage=)+ with_lock do+ reload+ day_key = current_day_key+ self.daily_usage = daily_usage.merge(day_key => daily_used + credits)++ # Inline JSONB cleanup (original behavior for backwards compatibility)+ cutoff = DAILY_USAGE_RETENTION_DAYS.days.ago.beginning_of_day.utc.strftime("%Y-%m-%d")+ self.daily_usage = daily_usage.select { |k, _| k >= cutoff }++ save!+ endendend@@ -137,16 +179,6 @@ class LlmCreditAllocation < ActiveRecord::Baseendprivate-- def cleanup_old_days!- cutoff = DAILY_USAGE_RETENTION_DAYS.days.ago.beginning_of_day.utc.strftime("%Y-%m-%d")- self.daily_usage = daily_usage.select { |k, _| k >= cutoff }- end-- def format_reset_time- return "" if next_reset_at.nil?- AgeWords.distance_of_time_in_words(next_reset_at, Time.now)- endend# == Schema Informationdiff --git a/plugins/discourse-ai/app/models/llm_credit_daily_usage.rb b/plugins/discourse-ai/app/models/llm_credit_daily_usage.rbnew file mode 100644index 00000000000..e3923628e3d--- /dev/null+++ b/plugins/discourse-ai/app/models/llm_credit_daily_usage.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++class LlmCreditDailyUsage < ActiveRecord::Base+ self.table_name = "llm_credit_daily_usages"++ belongs_to :llm_model++ validates :llm_model_id, presence: true+ validates :usage_date, presence: true+ validates :credits_used,+ presence: true,+ numericality: {+ only_integer: true,+ greater_than_or_equal_to: 0,+ }++ def self.find_or_create_for_today(llm_model)+ find_or_create_by!(llm_model: llm_model, usage_date: Date.current)+ end++ def self.increment_usage!(llm_model, credits)+ usage = find_or_create_for_today(llm_model)+ usage.with_lock { usage.increment!(:credits_used, credits) }+ end++ def self.usage_for_date(llm_model, date)+ find_by(llm_model: llm_model, usage_date: date)&.credits_used || 0+ end+end++# == Schema Information+#+# Table name: llm_credit_daily_usages+#+# id :bigint not null, primary key+# credits_used :bigint default(0), not null+# usage_date :date not null+# created_at :datetime not null+# updated_at :datetime not null+# llm_model_id :bigint not null+#+# Indexes+#+# index_llm_credit_daily_usages_on_llm_model_id (llm_model_id)+# index_llm_credit_daily_usages_on_llm_model_id_and_usage_date (llm_model_id,usage_date) UNIQUE+#diff --git a/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rb b/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rbindex 6be62711156..71ec37bcc07 100644--- a/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rb+++ b/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rb@@ -39,8 +39,12 @@ module DiscourseAillm_model_ids =personas.map { |p| p.default_llm_id || SiteSetting.ai_default_llm_model }.compact.uniq- # Batch load LLM models with their credit allocations- llm_models = LlmModel.where(id: llm_model_ids).includes(:llm_credit_allocation).index_by(&:id)+ # Batch load LLM models with their credit allocations and daily usage+ llm_models =+ LlmModel+ .where(id: llm_model_ids)+ .includes(llm_credit_allocation: :daily_usages)+ .index_by(&:id)personas.each do |persona|llm_model_id = persona.default_llm_id || SiteSetting.ai_default_llm_model@@ -76,11 +80,11 @@ module DiscourseAifeatures_with_models[feature_name] = llm_model.id if llm_modelend- # Batch load all LLM models+ # Batch load all LLM models with credit allocations and daily usagellm_models =LlmModel.where(id: llm_model_ids.compact.uniq)- .includes(:llm_credit_allocation)+ .includes(llm_credit_allocation: :daily_usages).index_by(&:id)features_with_models.each do |feature_name, llm_model_id|@@ -100,9 +104,12 @@ module DiscourseAicontext[:llm_models] = {}return true if params.llm_model_ids.blank?- # Batch load LLM models with their credit allocations+ # Batch load LLM models with their credit allocations and daily usagellm_models =- LlmModel.where(id: params.llm_model_ids).includes(:llm_credit_allocation).index_by(&:id)+ LlmModel+ .where(id: params.llm_model_ids)+ .includes(llm_credit_allocation: :daily_usages)+ .index_by(&:id)params.llm_model_ids.each do |id|llm_model = llm_models[id]diff --git a/plugins/discourse-ai/db/migrate/20251201225314_create_llm_credit_daily_usages.rb b/plugins/discourse-ai/db/migrate/20251201225314_create_llm_credit_daily_usages.rbnew file mode 100644index 00000000000..fa77d24415e--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20251201225314_create_llm_credit_daily_usages.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true+class CreateLlmCreditDailyUsages < ActiveRecord::Migration[8.0]+ def change+ create_table :llm_credit_daily_usages do |t|+ t.bigint :llm_model_id, null: false+ t.date :usage_date, null: false+ t.bigint :credits_used, null: false, default: 0+ t.timestamps+ end++ add_index :llm_credit_daily_usages, :llm_model_id+ add_index :llm_credit_daily_usages, %i[llm_model_id usage_date], unique: true+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20251201225946_backfill_llm_credit_daily_usages.rb b/plugins/discourse-ai/db/migrate/20251201225946_backfill_llm_credit_daily_usages.rbnew file mode 100644index 00000000000..e185282e78a--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20251201225946_backfill_llm_credit_daily_usages.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true+class BackfillLlmCreditDailyUsages < ActiveRecord::Migration[8.0]+ def up+ return unless column_exists?(:llm_credit_allocations, :daily_usage)++ # Migrate existing daily_usage JSONB data to the new table+ # This preserves all historical usage data+ execute <<~SQL+ INSERT INTO llm_credit_daily_usages (llm_model_id, usage_date, credits_used, created_at, updated_at)+ SELECT+ lca.llm_model_id,+ to_date(t.date_key, 'YYYY-MM-DD') as usage_date,+ t.credits::bigint as credits_used,+ NOW() as created_at,+ NOW() as updated_at+ FROM llm_credit_allocations lca,+ LATERAL jsonb_each_text(lca.daily_usage) AS t(date_key, credits)+ WHERE lca.daily_usage IS NOT NULL+ AND lca.daily_usage != '{}'::jsonb+ AND t.credits::integer > 0+ ON CONFLICT (llm_model_id, usage_date) DO UPDATE+ SET credits_used = EXCLUDED.credits_used,+ updated_at = NOW()+ SQL+ end++ def down+ # Intentionally left empty - we don't want to delete migrated data+ # The JSONB column will be removed in a separate migration+ end+enddiff --git a/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb b/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rbindex cdd6ea718cc..20fbfe158e5 100644--- a/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb+++ b/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb@@ -14,4 +14,16 @@ Fabricator(:llm_credit_allocation) doallocation.daily_usage = { day_key => transients[:daily_used] }endend++ after_create do |allocation, transients|+ if transients[:daily_used]+ # Also create the daily usage record in the new table+ usage =+ LlmCreditDailyUsage.find_or_create_by!(+ llm_model_id: allocation.llm_model_id,+ usage_date: Date.current,+ )+ usage.update!(credits_used: transients[:daily_used])+ end+ endenddiff --git a/plugins/discourse-ai/spec/models/llm_credit_daily_usage_spec.rb b/plugins/discourse-ai/spec/models/llm_credit_daily_usage_spec.rbnew file mode 100644index 00000000000..0e083f49b59--- /dev/null+++ b/plugins/discourse-ai/spec/models/llm_credit_daily_usage_spec.rb@@ -0,0 +1,121 @@+# frozen_string_literal: true++RSpec.describe LlmCreditDailyUsage do+ fab!(:llm_model)++ describe "validations" do+ it "requires llm_model_id" do+ usage = LlmCreditDailyUsage.new(usage_date: Date.current, credits_used: 100)+ expect(usage).not_to be_valid+ expect(usage.errors[:llm_model_id]).to be_present+ end++ it "requires usage_date" do+ usage = LlmCreditDailyUsage.new(llm_model: llm_model, credits_used: 100)+ expect(usage).not_to be_valid+ expect(usage.errors[:usage_date]).to be_present+ end++ it "requires credits_used to be non-negative" do+ usage =+ LlmCreditDailyUsage.new(llm_model: llm_model, usage_date: Date.current, credits_used: -1)+ expect(usage).not_to be_valid+ expect(usage.errors[:credits_used]).to be_present+ end++ it "enforces unique llm_model_id and usage_date combination" do+ LlmCreditDailyUsage.create!(llm_model: llm_model, usage_date: Date.current, credits_used: 100)++ duplicate =+ LlmCreditDailyUsage.new(llm_model: llm_model, usage_date: Date.current, credits_used: 200)++ expect { duplicate.save! }.to raise_error(ActiveRecord::RecordNotUnique)+ end++ it "allows same date for different models" do+ other_model = Fabricate(:llm_model)++ LlmCreditDailyUsage.create!(llm_model: llm_model, usage_date: Date.current, credits_used: 100)++ usage =+ LlmCreditDailyUsage.new(llm_model: other_model, usage_date: Date.current, credits_used: 200)++ expect(usage).to be_valid+ end+ end++ describe ".find_or_create_for_today" do+ it "creates a new record for today if none exists" do+ usage = LlmCreditDailyUsage.find_or_create_for_today(llm_model)++ expect(usage).to be_persisted+ expect(usage.llm_model_id).to eq(llm_model.id)+ expect(usage.usage_date).to eq(Date.current)+ expect(usage.credits_used).to eq(0)+ end++ it "returns existing record for today" do+ existing =+ LlmCreditDailyUsage.create!(+ llm_model: llm_model,+ usage_date: Date.current,+ credits_used: 100,+ )++ usage = LlmCreditDailyUsage.find_or_create_for_today(llm_model)++ expect(usage.id).to eq(existing.id)+ expect(usage.credits_used).to eq(100)+ end+ end++ describe ".increment_usage!" do+ it "creates record and increments when none exists" do+ LlmCreditDailyUsage.increment_usage!(llm_model, 50)++ usage = LlmCreditDailyUsage.find_by(llm_model: llm_model, usage_date: Date.current)+ expect(usage.credits_used).to eq(50)+ end++ it "increments existing record" do+ LlmCreditDailyUsage.create!(llm_model: llm_model, usage_date: Date.current, credits_used: 100)++ LlmCreditDailyUsage.increment_usage!(llm_model, 50)++ usage = LlmCreditDailyUsage.find_by(llm_model: llm_model, usage_date: Date.current)+ expect(usage.credits_used).to eq(150)+ end++ it "handles concurrent increments correctly" do+ threads = []+ 5.times { threads << Thread.new { LlmCreditDailyUsage.increment_usage!(llm_model, 10) } }+ threads.each(&:join)++ usage = LlmCreditDailyUsage.find_by(llm_model: llm_model, usage_date: Date.current)+ expect(usage.credits_used).to eq(50)+ end+ end++ describe ".usage_for_date" do+ it "returns credits for existing date" do+ LlmCreditDailyUsage.create!(llm_model: llm_model, usage_date: Date.current, credits_used: 250)++ expect(LlmCreditDailyUsage.usage_for_date(llm_model, Date.current)).to eq(250)+ end++ it "returns 0 for date with no record" do+ expect(LlmCreditDailyUsage.usage_for_date(llm_model, Date.current)).to eq(0)+ end++ it "returns 0 for different model" do+ other_model = Fabricate(:llm_model)+ LlmCreditDailyUsage.create!(+ llm_model: other_model,+ usage_date: Date.current,+ credits_used: 250,+ )++ expect(LlmCreditDailyUsage.usage_for_date(llm_model, Date.current)).to eq(0)+ end+ end+end