Skip to content

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.rb
index 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 DiscourseAi
return 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_allocation
allocation.update!(credit_allocation_params)
elsif llm_model.llm_credit_allocation
llm_model.llm_credit_allocation.destroy
diff --git a/plugins/discourse-ai/app/models/llm_credit_allocation.rb b/plugins/discourse-ai/app/models/llm_credit_allocation.rb
index 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::Base
belongs_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: true
validates :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::Base
greater_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)
+ end
def credits_remaining
[0, monthly_credits - monthly_used].max
@@ -64,28 +71,15 @@ class LlmCreditAllocation < ActiveRecord::Base
end
def 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_month
end
def 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!
end
end
@@ -112,7 +106,6 @@ class LlmCreditAllocation < ActiveRecord::Base
allocation = llm_model.llm_credit_allocation
return true unless allocation
- allocation.reset_if_needed!
allocation.credits_available?
end
@@ -120,7 +113,6 @@ class LlmCreditAllocation < ActiveRecord::Base
return 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::Base
private
- 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 }
end
def 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 null
diff --git a/plugins/discourse-ai/app/serializers/llm_credit_allocation_serializer.rb b/plugins/discourse-ai/app/serializers/llm_credit_allocation_serializer.rb
index 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.rb
index 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 < ProblemCheck
next unless model.llm_credit_allocation
allocation = model.llm_credit_allocation
- allocation.reset_if_needed!
problems << hard_limit_problem(model, allocation) if allocation.hard_limit_reached?
end
diff --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.rb
index 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 < ProblemCheck
next unless model.llm_credit_allocation
allocation = 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.rb
new file mode 100644
index 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
+end
diff --git a/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb b/plugins/discourse-ai/spec/fabricators/llm_credit_allocation_fabricator.rb
index 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) do
llm_model
monthly_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
+ end
end
diff --git a/plugins/discourse-ai/spec/models/llm_credit_allocation_spec.rb b/plugins/discourse-ai/spec/models/llm_credit_allocation_spec.rb
index 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 do
expect(allocation).to be_valid
end
- 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" do
allocation = 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)
end
end
@@ -225,90 +218,61 @@ RSpec.describe LlmCreditAllocation do
end
describe "#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" do
freeze_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"))
end
end
- 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 <= 7
end
end
@@ -384,34 +348,32 @@ RSpec.describe LlmCreditAllocation do
expect(LlmCreditAllocation.credits_available?(llm_model)).to be false
end
- 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)
end
end
describe "#formatted_reset_time" do
it "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}/)
end
it "returns empty string when next_reset_at is nil" do
@@ -424,12 +386,11 @@ RSpec.describe LlmCreditAllocation do
describe "#relative_reset_time" do
it "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 .+/)
end
it "returns empty string when next_reset_at is nil" do
diff --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.rb
index 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 do
expect(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.call
expect(problems).to be_empty
diff --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.rb
index 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 do
expect(problems).to be_empty
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: 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.call
expect(problems).to be_empty