A platform for community discussion. Free, open, simple.
DEV: Update handling of monthly credit resets (#35839)
Keegan Georgea95a5448a7e7
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rbindex fb42b19e938..5f6f6b40a08 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb@@ -318,9 +318,7 @@ module DiscourseAireturn unless llm_model.seeded? && params[:ai_llm].key?(:llm_credit_allocation)if credit_allocation_params- allocation =- llm_model.llm_credit_allocation ||- llm_model.build_llm_credit_allocation(last_reset_at: Time.current)+ allocation = llm_model.llm_credit_allocation || llm_model.build_llm_credit_allocationallocation.update!(credit_allocation_params)elsif llm_model.llm_credit_allocationllm_model.llm_credit_allocation.destroydiff --git a/plugins/discourse-ai/app/models/llm_credit_allocation.rb b/plugins/discourse-ai/app/models/llm_credit_allocation.rbindex 2d1d1fa887e..077e33bf7cf 100644--- a/plugins/discourse-ai/app/models/llm_credit_allocation.rb+++ b/plugins/discourse-ai/app/models/llm_credit_allocation.rb@@ -14,14 +14,11 @@ class LlmCreditAllocation < ActiveRecord::Basebelongs_to :llm_model+ # TODO: Remove once 20251105174002_refactor_llm_credit_allocation_to_monthly_usage has been promoted to pre-deploy+ self.ignored_columns = %w[monthly_used last_reset_at]+validates :llm_model_id, presence: true, uniqueness: truevalidates :monthly_credits, presence: true, numericality: { only_integer: true, greater_than: 0 }- validates :monthly_used,- presence: true,- numericality: {- only_integer: true,- greater_than_or_equal_to: 0,- }validates :soft_limit_percentage,presence: true,numericality: {@@ -29,9 +26,19 @@ class LlmCreditAllocation < ActiveRecord::Basegreater_than_or_equal_to: 0,less_than_or_equal_to: 100,}- validates :last_reset_at, presence: true- before_validation :set_last_reset_at, on: :create+ def current_month_key+ Time.current.strftime("%Y-%m")+ end++ def monthly_used+ monthly_usage[current_month_key].to_i+ end++ def monthly_used=(value)+ month_key = current_month_key+ self.monthly_usage = (monthly_usage || {}).merge(month_key => value.to_i)+ enddef credits_remaining[0, monthly_credits - monthly_used].max@@ -64,28 +71,15 @@ class LlmCreditAllocation < ActiveRecord::Baseenddef next_reset_at- return nil if last_reset_at.nil?- (last_reset_at + 1.month).beginning_of_month- end-- def reset_if_needed!- with_lock do- reload- return unless should_reset?-- now = Time.current.beginning_of_month- update!(monthly_used: 0, last_reset_at: now)- end- end-- def should_reset?- return false if last_reset_at.nil?- Time.current >= next_reset_at+ Time.current.next_month.beginning_of_monthenddef deduct_credits!(credits)with_lock do- self.monthly_used += credits+ reload+ month_key = current_month_key+ self.monthly_usage = monthly_usage.merge(month_key => monthly_used + credits)+ cleanup_old_months!save!endend@@ -112,7 +106,6 @@ class LlmCreditAllocation < ActiveRecord::Baseallocation = llm_model.llm_credit_allocationreturn true unless allocation- allocation.reset_if_needed!allocation.credits_available?end@@ -120,7 +113,6 @@ class LlmCreditAllocation < ActiveRecord::Basereturn unless llm_model&.credit_system_enabled?allocation = llm_model.llm_credit_allocation- allocation.reset_if_needed!allocation.check_credits!end@@ -144,8 +136,9 @@ class LlmCreditAllocation < ActiveRecord::Baseprivate- def set_last_reset_at- self.last_reset_at ||= Time.current.beginning_of_month+ def cleanup_old_months!+ cutoff = 6.months.ago.beginning_of_month.strftime("%Y-%m")+ self.monthly_usage = monthly_usage.select { |k, _| k >= cutoff }enddef format_reset_time@@ -159,9 +152,8 @@ end# Table name: llm_credit_allocations## id :bigint not null, primary key-# last_reset_at :datetime not null# monthly_credits :bigint not null-# monthly_used :bigint default(0), not null+# monthly_usage :jsonb not null# soft_limit_percentage :integer default(80), not null# created_at :datetime not null# updated_at :datetime not nulldiff --git a/plugins/discourse-ai/app/serializers/llm_credit_allocation_serializer.rb b/plugins/discourse-ai/app/serializers/llm_credit_allocation_serializer.rbindex d406672dd84..7d5db19f007 100644--- a/plugins/discourse-ai/app/serializers/llm_credit_allocation_serializer.rb+++ b/plugins/discourse-ai/app/serializers/llm_credit_allocation_serializer.rb@@ -7,7 +7,6 @@ class LlmCreditAllocationSerializer < ApplicationSerializer:credits_remaining,:percentage_used,:percentage_remaining,- :last_reset_at,:next_reset_at,:soft_limit_percentage,:soft_limit_reached,diff --git a/plugins/discourse-ai/app/services/problem_check/ai_credit_hard_limit.rb b/plugins/discourse-ai/app/services/problem_check/ai_credit_hard_limit.rbindex bf7f902fb0c..b0221335199 100644--- a/plugins/discourse-ai/app/services/problem_check/ai_credit_hard_limit.rb+++ b/plugins/discourse-ai/app/services/problem_check/ai_credit_hard_limit.rb@@ -16,7 +16,6 @@ class ProblemCheck::AiCreditHardLimit < ProblemChecknext unless model.llm_credit_allocationallocation = model.llm_credit_allocation- allocation.reset_if_needed!problems << hard_limit_problem(model, allocation) if allocation.hard_limit_reached?enddiff --git a/plugins/discourse-ai/app/services/problem_check/ai_credit_soft_limit.rb b/plugins/discourse-ai/app/services/problem_check/ai_credit_soft_limit.rbindex 8966d509b16..3b1c31fab75 100644--- a/plugins/discourse-ai/app/services/problem_check/ai_credit_soft_limit.rb+++ b/plugins/discourse-ai/app/services/problem_check/ai_credit_soft_limit.rb@@ -16,7 +16,6 @@ class ProblemCheck::AiCreditSoftLimit < ProblemChecknext unless model.llm_credit_allocationallocation = model.llm_credit_allocation- allocation.reset_if_needed!if allocation.soft_limit_reached? && !allocation.hard_limit_reached?problems << soft_limit_problem(model, allocation)diff --git a/plugins/discourse-ai/db/post_migrate/20251105174002_refactor_llm_credit_allocation_to_monthly_usage.rb b/plugins/discourse-ai/db/post_migrate/20251105174002_refactor_llm_credit_allocation_to_monthly_usage.rbnew file mode 100644index 00000000000..90ee901e2d2--- /dev/null+++ b/plugins/discourse-ai/db/post_migrate/20251105174002_refactor_llm_credit_allocation_to_monthly_usage.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true+class RefactorLlmCreditAllocationToMonthlyUsage < ActiveRecord::Migration[8.0]+ def up+ add_column :llm_credit_allocations, :monthly_usage, :jsonb, default: {}, null: false++ execute <<~SQL+ UPDATE llm_credit_allocations+ SET monthly_usage = jsonb_build_object(+ to_char(COALESCE(last_reset_at, CURRENT_TIMESTAMP), 'YYYY-MM'),+ monthly_used+ )+ WHERE monthly_used > 0+ SQL++ remove_column :llm_credit_allocations, :monthly_used+ remove_column :llm_credit_allocations, :last_reset_at+ end++ def down+ add_column :llm_credit_allocations, :monthly_used, :bigint, default: 0, null: false+ add_column :llm_credit_allocations,+ :last_reset_at,+ :datetime,+ null: false,+ default: -> { "date_trunc('month', CURRENT_TIMESTAMP)" }++ execute <<~SQL+ UPDATE llm_credit_allocations+ SET monthly_used = COALESCE(+ (monthly_usage->>to_char(CURRENT_TIMESTAMP, 'YYYY-MM'))::bigint,+ 0+ ),+ last_reset_at = date_trunc('month', CURRENT_TIMESTAMP)+ SQL++ remove_column :llm_credit_allocations, :monthly_usage+ 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 e73b6e814e4..e7789fb060b 100644--- a/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb+++ b/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb@@ -3,7 +3,15 @@Fabricator(:llm_credit_allocation) dollm_modelmonthly_credits 1_000_000- monthly_used 0- last_reset_at { Time.current.beginning_of_month }+ monthly_usage { {} }soft_limit_percentage 80++ transient :monthly_used++ after_build do |allocation, transients|+ if transients[:monthly_used]+ month_key = Time.current.strftime("%Y-%m")+ allocation.monthly_usage = { month_key => transients[:monthly_used] }+ end+ endenddiff --git a/plugins/discourse-ai/spec/models/llm_credit_allocation_spec.rb b/plugins/discourse-ai/spec/models/llm_credit_allocation_spec.rbindex c92eb320154..4c410a3c22b 100644--- a/plugins/discourse-ai/spec/models/llm_credit_allocation_spec.rb+++ b/plugins/discourse-ai/spec/models/llm_credit_allocation_spec.rb@@ -36,17 +36,10 @@ RSpec.describe LlmCreditAllocation doexpect(allocation).to be_validend- it "sets last_reset_at on create" do- allocation = Fabricate.build(:llm_credit_allocation, llm_model: llm_model)- allocation.last_reset_at = nil- allocation.save!- expect(allocation.last_reset_at).to be_present- end-- it "sets last_reset_at to beginning of month on create" do- freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ it "initializes with empty monthly_usage on create" doallocation = Fabricate(:llm_credit_allocation, llm_model: llm_model)- expect(allocation.last_reset_at).to eq_time(Time.zone.parse("2025-10-01 00:00:00"))+ expect(allocation.monthly_usage).to eq({})+ expect(allocation.monthly_used).to eq(0)endend@@ -225,90 +218,61 @@ RSpec.describe LlmCreditAllocation doenddescribe "#next_reset_at" do- it "returns beginning of next month after last_reset_at" do- freeze_time- allocation = Fabricate(:llm_credit_allocation, last_reset_at: Time.current)- expect(allocation.next_reset_at).to eq_time((1.month.from_now).beginning_of_month)+ it "returns first of next month" do+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ allocation = Fabricate(:llm_credit_allocation)+ expect(allocation.next_reset_at).to eq_time(Time.zone.parse("2025-11-01 00:00:00"))end- it "returns first of next month when created mid-month" do- freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ it "returns first of next month when on last day of month" do+ freeze_time(Time.zone.parse("2025-10-31 23:59:00"))allocation = Fabricate(:llm_credit_allocation)- expect(allocation.last_reset_at).to eq_time(Time.zone.parse("2025-10-01 00:00:00"))expect(allocation.next_reset_at).to eq_time(Time.zone.parse("2025-11-01 00:00:00"))end- it "returns first of next month when created on first of month" do+ it "returns first of next month when on first of month" dofreeze_time(Time.zone.parse("2025-11-01 00:00:00"))allocation = Fabricate(:llm_credit_allocation)- expect(allocation.last_reset_at).to eq_time(Time.zone.parse("2025-11-01 00:00:00"))expect(allocation.next_reset_at).to eq_time(Time.zone.parse("2025-12-01 00:00:00"))endend- describe "#should_reset?" do- it "returns true when time has passed next_reset_at" do- allocation = Fabricate(:llm_credit_allocation, last_reset_at: 2.months.ago)- expect(allocation.should_reset?).to be true- end+ describe "month transitions" do+ it "automatically resets usage to 0 when month changes" do+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ allocation = Fabricate(:llm_credit_allocation, monthly_credits: 1000, monthly_used: 800)+ expect(allocation.monthly_used).to eq(800)- it "returns false when before next_reset_at" do- allocation = Fabricate(:llm_credit_allocation, last_reset_at: 1.day.ago)- expect(allocation.should_reset?).to be false+ freeze_time(Time.zone.parse("2025-11-05 10:00:00"))+ allocation.reload+ expect(allocation.monthly_used).to eq(0)end- end- describe "#reset_if_needed!" do- it "resets credits when time has passed" do- allocation =- Fabricate(- :llm_credit_allocation,- monthly_credits: 1000,- monthly_used: 800,- last_reset_at: 2.months.ago,- )+ it "preserves previous month's data" do+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ allocation = Fabricate(:llm_credit_allocation, monthly_credits: 1000, monthly_used: 800)- freeze_time do- allocation.reset_if_needed!+ freeze_time(Time.zone.parse("2025-11-05 10:00:00"))+ allocation.deduct_credits!(200)+ allocation.reload- allocation.reload- expect(allocation.monthly_used).to eq(0)- expect(allocation.last_reset_at).to eq_time(Time.current.beginning_of_month)- end+ expect(allocation.monthly_used).to eq(200)+ expect(allocation.monthly_usage["2025-10"]).to eq(800)end- it "does not reset when time has not passed" do- original_time = 1.day.ago- allocation =- Fabricate(- :llm_credit_allocation,- monthly_credits: 1000,- monthly_used: 800,- last_reset_at: original_time,- )+ it "cleans up old months beyond 6 months" do+ allocation = Fabricate(:llm_credit_allocation)- allocation.reset_if_needed!+ 8.times do |i|+ month_key = (i + 1).months.ago.strftime("%Y-%m")+ allocation.monthly_usage[month_key] = 1000 * (i + 1)+ end+ allocation.save!+ allocation.deduct_credits!(100)allocation.reload- expect(allocation.monthly_used).to eq(800)- expect(allocation.last_reset_at).to be_within(1.second).of(original_time)- end-- it "resets to beginning of current month when triggered mid-month" do- freeze_time(Time.zone.parse("2025-10-15 14:30:00"))- allocation =- Fabricate(- :llm_credit_allocation,- monthly_credits: 1000,- monthly_used: 800,- last_reset_at: Time.zone.parse("2025-09-01 00:00:00"),- )-- allocation.reset_if_needed!- allocation.reload- expect(allocation.monthly_used).to eq(0)- expect(allocation.last_reset_at).to eq_time(Time.zone.parse("2025-10-01 00:00:00"))+ expect(allocation.monthly_usage.keys.size).to be <= 7endend@@ -384,34 +348,32 @@ RSpec.describe LlmCreditAllocation doexpect(LlmCreditAllocation.credits_available?(llm_model)).to be falseend- it "resets and returns true when reset is needed" do+ it "returns true when previous month hit limit but current month is new" do+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))allocation =Fabricate(:llm_credit_allocation,llm_model: llm_model,monthly_credits: 1000,monthly_used: 1000,- last_reset_at: 2.months.ago,)- freeze_time do- result = LlmCreditAllocation.credits_available?(llm_model)+ freeze_time(Time.zone.parse("2025-11-05 10:00:00"))+ result = LlmCreditAllocation.credits_available?(llm_model)- allocation.reload- expect(result).to be true- expect(allocation.monthly_used).to eq(0)- end+ allocation.reload+ expect(result).to be true+ expect(allocation.monthly_used).to eq(0)endenddescribe "#formatted_reset_time" doit "returns formatted reset time" do- freeze_time do- allocation = Fabricate(:llm_credit_allocation, last_reset_at: Time.current)- formatted = allocation.formatted_reset_time+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ allocation = Fabricate(:llm_credit_allocation)+ formatted = allocation.formatted_reset_time- expect(formatted).to match(/\d{1,2}:\d{2}[ap]m on \w+ \d{1,2}, \d{4}/)- end+ expect(formatted).to match(/\d{1,2}:\d{2}[ap]m on \w+ \d{1,2}, \d{4}/)endit "returns empty string when next_reset_at is nil" do@@ -424,12 +386,11 @@ RSpec.describe LlmCreditAllocation dodescribe "#relative_reset_time" doit "returns relative time until reset" do- freeze_time do- allocation = Fabricate(:llm_credit_allocation, last_reset_at: Time.current)- relative = allocation.relative_reset_time+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))+ allocation = Fabricate(:llm_credit_allocation)+ relative = allocation.relative_reset_time- expect(relative).to match(/in .+/)- end+ expect(relative).to match(/in .+/)endit "returns empty string when next_reset_at is nil" dodiff --git a/plugins/discourse-ai/spec/services/problem_check/ai_credit_hard_limit_spec.rb b/plugins/discourse-ai/spec/services/problem_check/ai_credit_hard_limit_spec.rbindex bb7e995bd89..6be2f628a77 100644--- a/plugins/discourse-ai/spec/services/problem_check/ai_credit_hard_limit_spec.rb+++ b/plugins/discourse-ai/spec/services/problem_check/ai_credit_hard_limit_spec.rb@@ -58,17 +58,18 @@ RSpec.describe ProblemCheck::AiCreditHardLimit doexpect(problems.first.identifier).to eq(:ai_credit_hard_limit)end- it "resets credits before checking if needed" do+ it "does not report problem when previous month exceeded limit but current month is new" do+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))allocation =Fabricate(:llm_credit_allocation,llm_model: llm_model,monthly_credits: 1000,monthly_used: 1000,- last_reset_at: 2.months.ago,soft_limit_percentage: 80,)+ freeze_time(Time.zone.parse("2025-11-05 10:00:00"))problems = described_class.new.callexpect(problems).to be_emptydiff --git a/plugins/discourse-ai/spec/services/problem_check/ai_credit_soft_limit_spec.rb b/plugins/discourse-ai/spec/services/problem_check/ai_credit_soft_limit_spec.rbindex 564ebf38705..689a45e5b70 100644--- a/plugins/discourse-ai/spec/services/problem_check/ai_credit_soft_limit_spec.rb+++ b/plugins/discourse-ai/spec/services/problem_check/ai_credit_soft_limit_spec.rb@@ -57,17 +57,18 @@ RSpec.describe ProblemCheck::AiCreditSoftLimit doexpect(problems).to be_emptyend- it "resets credits before checking if needed" do+ it "does not report problem when previous month exceeded limit but current month is new" do+ freeze_time(Time.zone.parse("2025-10-15 14:30:00"))allocation =Fabricate(:llm_credit_allocation,llm_model: llm_model,monthly_credits: 1000,monthly_used: 850,- last_reset_at: 2.months.ago,soft_limit_percentage: 80,)+ freeze_time(Time.zone.parse("2025-11-05 10:00:00"))problems = described_class.new.callexpect(problems).to be_empty