Skip to content

fix: totalAvailableGrantAmount - #4304

Merged
GAlexIHU merged 2 commits into
mainfrom
fix/totalavailablegrant
May 6, 2026
Merged

GAlexIHU merged 2 commits into
mainfrom
fix/totalavailablegrant

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Fixes #(issue)

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Segmented grant-usage history and precise decimal-based accounting for more accurate usage totals.
    • Phase planning now guarantees at least one phase per period and emits a terminal no-op phase when needed.
  • Bug Fixes

    • More accurate total-available-grant metric based on last-period state.
    • Improved recurrence/effective-boundary handling to correctly include/exclude period endpoints.
  • Tests

    • Added comprehensive tests for history chunking and run-result grant calculations.

@GAlexIHU
GAlexIHU requested a review from a team as a code owner May 6, 2026 14:20
@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label May 6, 2026
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR makes phase planning recurrence-aware at period end, adds guards and terminal-phase handling in phase emission, shifts grant-availability calculation to use last-period usage plus current snapshot, introduces history chunking and decimal usage aggregation, and adds tests covering history chunking and the new availability logic.

Changes

Recurrence Boundary-Aware Phase Planning

Layer / File(s) Summary
Data Shape & Phase Guards
openmeter/credit/engine/burnphase.go
getPhases signature now accepts recurrenceEndBoundaryBehavior; appendPhase ignores zero/negative-duration phases.
Recurrence Time Calculation
openmeter/credit/engine/grant.go
getGrantRecurrenceTimes extended with endBoundaryBehavior; period-boundary checks now use boundary-aware containment (inclusive/exclusive) and handle zero-length periods.
Boundary Configuration & Plumbing
openmeter/credit/engine/run.go
Added PeriodEndRecurrenceBoundaryBehavior to in-between-run params; runBetweenResets passes inclusive for final period and exclusive otherwise into phase planning.
Phase Emission & Terminal Handling
openmeter/credit/engine/burnphase.go
Phase emission moved to occur unconditionally after computation (guard filters invalid ones); adds zero-length terminal phase at period end when last phase ends at period end with end-grants; ensures at least one full-period phase if none produced.

Grant Availability & History Tracking

Layer / File(s) Summary
History Chunking & Aggregation
openmeter/credit/engine/history.go
Added ChunkByResets() to split histories at UsageReset boundaries, TotalGrantUsage() returning a decimal, and usageAtReset helper to create starting snapshots.
Grant Amount Calculation
openmeter/credit/engine/engine.go
Removed TotalAvailableGrantAmount(); added TotalAvailableGrantAmountAtLastPeriod() which computes available grant amount as last-period usage plus current snapshot balance (returned as float).
Consumer Integration
openmeter/entitlement/metered/balance.go
GetEntitlementBalance now sources TotalAvailableGrantAmountAtLastPeriod(); EntitlementBalance got inline field comments only.
Tests
openmeter/credit/engine/history_test.go, openmeter/credit/engine/runresult_test.go
New tests: history chunking behavior and comprehensive scenarios validating TotalAvailableGrantAmountAtLastPeriod across various grant/recurrence/reset/rollover cases.

Sequence Diagram(s)

sequenceDiagram
    participant Runner
    participant Engine
    participant GrantRecurrence as RecurrenceCalculator
    participant History
    participant Entitlement

    Runner->>Engine: Run(periods, grants, snapshot)
    Engine->>GrantRecurrence: getGrantRecurrenceTimes(..., endBoundaryBehavior)
    GrantRecurrence-->>Engine: recurrence timestamps (boundary-aware)
    Engine->>Engine: build phases (appendPhase guard, terminal handling)
    Engine->>History: ChunkByResets() / TotalGrantUsage()
    History-->>Engine: usage per chunk / last-period usage
    Engine->>Engine: TotalAvailableGrantAmountAtLastPeriod = last-period-usage + snapshot.balance
    Engine->>Entitlement: GetEntitlementBalance uses TotalAvailableGrantAmountAtLastPeriod
    Entitlement-->>Runner: EntitlementBalance
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • openmeterio/openmeter#4278: Modifies the same phase/recurrence boundary logic in burnphase.go and getGrantRecurrenceTimes to handle period end boundary behavior.
  • openmeterio/openmeter#4252: Related to recurrence handling in the run flow; overlaps conceptually with recurrence plumbing and runBetweenResets changes.

Suggested reviewers

  • tothandras
  • chrisgacsal
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: totalAvailableGrantAmount' directly aligns with the main change: replacing the old TotalAvailableGrantAmount() method with TotalAvailableGrantAmountAtLastPeriod() across the codebase.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/totalavailablegrant

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (8)
openmeter/credit/engine/engine.go (1)

59-67: 💤 Low value

Nice clean implementation — small heads-up on the empty-history path.

lo.Last returns the zero value when ChunkByResets() is empty (e.g. a run with no segments at all), so this method falls back to 0 + Snapshot.Balance(). That's likely the desired graceful default, but it's worth a one-liner comment so future readers know the empty case is intentional and not a missed ok check.

📝 Tiny doc nudge
 // TotalAvailableGrantAmountAtLastPeriod is the total grant amount available in the run period:
 // grant-covered usage plus remaining balances still available at the end.
+// If the history is empty (no segments) we fall back to just the end-of-period balance.
 func (r RunResult) TotalAvailableGrantAmountAtLastPeriod() float64 {
-	lastUsagePeriodHistory, _ := lo.Last(r.History.ChunkByResets())
+	lastUsagePeriodHistory, _ := lo.Last(r.History.ChunkByResets())
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/engine.go` around lines 59 - 67, Add a one-line
comment to RunResult.TotalAvailableGrantAmountAtLastPeriod explaining that
lo.Last(r.History.ChunkByResets()) intentionally returns the zero value for
empty history so the computation falls back to Snapshot.Balance(); locate the
method TotalAvailableGrantAmountAtLastPeriod on the RunResult type and insert a
concise note above the call to lo.Last indicating the empty-history case is
intentional and expected.
openmeter/credit/engine/runresult_test.go (2)

22-23: 💤 Low value

Tiny test ergonomics: prefer require.NoError for setup that can't recover.

time.Parse failing here would invalidate the entire test, but assert.NoError lets execution continue and you'd hit a nil/zero-time fallout further down. Swapping to require.NoError (you already import require) gives a cleaner failure surface.

♻️ Suggested tweak
-	t1, err := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
-	assert.NoError(t, err)
+	t1, err := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
+	require.NoError(t, err)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/runresult_test.go` around lines 22 - 23, In
runresult_test.go change the setup assertion that checks time.Parse from using
assert.NoError to require.NoError so the test stops immediately on parse
failure; locate the time.Parse call that assigns t1 and replace the assert usage
with require (you already import require) to prevent downstream nil/zero-time
errors during the test.

42-51: 💤 Low value

Drop the commented-out grant2 block before merging?

Either wire it into a test or remove it — leaving large commented-out blocks tends to bit-rot quickly and a future reader won't know if it was intentional scaffolding or a forgotten todo.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/runresult_test.go` around lines 42 - 51, Remove the
large commented-out grant2 test scaffold: delete the commented block that
defines grant2 (the makeGrant(grant.Grant{...}) snippet) rather than leaving it
in the file; if you actually need that extra test case instead, wire it into the
existing test by uncommenting and using the grant2 variable where appropriate
(referencing makeGrant, grant.Grant, grant.ExpirationPeriod and
grant.ExpirationPeriodDurationDay) — otherwise delete the commented lines to
avoid bit-rot.
openmeter/credit/engine/history.go (1)

166-193: 💤 Low value

Looks solid — one optional readability tweak.

The chunking logic is straightforward and the empty-trailing-chunk guard at the end is exactly right. A small thing: every fresh current over-allocates capacity to len(g.segments) even when there are many resets. For typical histories this is negligible, but if you wanted to be tidy you could size based on remaining segments — purely cosmetic.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/history.go` around lines 166 - 193, In ChunkByResets,
avoid over-allocating current.segments to len(g.segments) for every new chunk:
when constructing the initial current and each reset-created current, set the
capacity to the number of remaining segments instead (e.g., remaining :=
len(g.segments) - index or similar) so current.segments is allocated with
capacity based on remaining segments; update the places creating
GrantBurnDownHistory with segments to use that remaining count while keeping the
same behavior for usageAtStart and usageAtReset.
openmeter/credit/engine/run.go (1)

47-89: ⚡ Quick win

Cache timeline.GetClosedPeriods() once — both for clarity and perf.

timeline.GetClosedPeriods() is invoked inside the loop body twice per iteration (line 65 and line 74), in addition to the range expression. If GetClosedPeriods() rebuilds a slice on each call, that's O(n²) on a hot path; even if it's cheap, repeating the call hurts readability and invites bugs if the timeline ever becomes mutable. Pulling it out once also lets the boundary ternary read more naturally.

♻️ Suggested cleanup
-	for idx, period := range timeline.GetClosedPeriods() {
+	periods := timeline.GetClosedPeriods()
+	lastIdx := len(periods) - 1
+	for idx, period := range periods {
 		// Let's reset the snapshot usage information as we're entering a new period (between resets)
 		if idx > 0 {
 			snapshot.Usage = balance.SnapshottedUsage{
 				Since: period.From,
 				Usage: 0.0,
 			}
 		}
 
 		// We need to find the grants that are relevant for this period.
 		// We do this filtering so that history isn't polluted with grants that are irrelevant.
 		relevantGrants := e.filterRelevantGrants(params.Grants, snapshot.Balances, period)
 
 		runRes, err := e.runBetweenResets(ctx, inbetweenRunParams{
 			Grants:                              relevantGrants,
 			Until:                               period.To,
 			StartingSnapshot:                    snapshot,
 			Meter:                               params.Meter,
-			PeriodEndRecurrenceBoundaryBehavior: lo.Ternary(idx == len(timeline.GetClosedPeriods())-1, timeutil.Inclusive, timeutil.Exclusive),
+			PeriodEndRecurrenceBoundaryBehavior: lo.Ternary(idx == lastIdx, timeutil.Inclusive, timeutil.Exclusive),
 		})
 		if err != nil {
 			return RunResult{}, fmt.Errorf("failed to run calculation for period %s - %s: %w", period.From, period.To, err)
 		}
 
 		snapshot = runRes.Snapshot
 		historySegments = append(historySegments, runRes.History.Segments()...)
 
-		if idx != len(timeline.GetClosedPeriods())-1 {
+		if idx != lastIdx {
 			// We need to reset at each period, except the last one.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/run.go` around lines 47 - 89, The loop calls
timeline.GetClosedPeriods() multiple times per iteration (in the range, in the
ternary and in the slice length check), which can be costly and confusing; fix
by calling timeline.GetClosedPeriods() once before the loop (e.g., closed :=
timeline.GetClosedPeriods()) and iterate over closed with for idx, period :=
range closed, then replace other uses (lo.Ternary idx == len(closed)-1 and
similar checks) to reference closed; update any comments if needed and ensure
variables passed to e.runBetweenResets, inbetweenRunParams, and e.reset remain
the same.
openmeter/credit/engine/grant.go (2)

65-70: 💤 Low value

Tiny readability nit: that anonymous return type.

Returning []struct { time time.Time; grantIDs []string } (and signing it inline in the func signature) is functional but a bit gnarly to read and reuse. If you ever want to expose this or write helpers around it, a named type would pay off. Totally optional — not blocking.

♻️ Possible refactor
+type grantRecurrenceTime struct {
+	time     time.Time
+	grantIDs []string
+}
+
-func (e *engine) getGrantRecurrenceTimes(grants []grant.Grant, period timeutil.ClosedPeriod, endBoundaryBehavior timeutil.Boundary) ([]struct {
-	time     time.Time
-	grantIDs []string
-}, error,
-) {
+func (e *engine) getGrantRecurrenceTimes(grants []grant.Grant, period timeutil.ClosedPeriod, endBoundaryBehavior timeutil.Boundary) ([]grantRecurrenceTime, error) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/grant.go` around lines 65 - 70, The current
getGrantRecurrenceTimes function returns an inline anonymous slice type
([]struct { time time.Time; grantIDs []string }) which hurts readability and
reuse; introduce a small named type (e.g., GrantRecurrence or
grantRecurrenceTime) in the same package with fields Time time.Time and GrantIDs
[]string, replace the anonymous return type in the getGrantRecurrenceTimes
signature and all uses/returns inside that function to use the new named type,
and update any references or tests that expect the old anonymous shape to
compile against the new type name.

96-111: 💤 Low value

Heads up: silent fallthrough on unknown Boundary values.

The default branch in inPeriod returns false, so if a new timeutil.Boundary kind ever shows up the recurrence times at the boundary would be silently dropped instead of surfacing as a clear error. Since Boundary is a closed set today this is fine, but a small guard would make this future-proof.

♻️ Optional tweak
 			switch behavior {
 			case timeutil.Inclusive:
 				return period.ContainsInclusive(at) // [from, to]
 			case timeutil.Exclusive:
 				return period.Contains(at) // [from, to)
 			default:
-				return false
+				// Unknown boundary behavior; fail loudly instead of silently dropping.
+				panic(fmt.Sprintf("unknown boundary behavior: %v", behavior))
 			}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/grant.go` around lines 96 - 111, The inPeriod closure
silently returns false on an unknown timeutil.Boundary which can hide future
bugs; update the default branch in the inPeriod function (referencing
endBoundaryBehavior and the timeutil.Boundary enum) to surface an explicit error
(e.g. panic or log.Fatalf with the unexpected boundary value) instead of
returning false so unknown boundary kinds fail loudly, and include the boundary
value in the message to aid debugging; keep the existing cases calling
period.ContainsInclusive and period.Contains unchanged.
openmeter/credit/engine/burnphase.go (1)

137-154: ⚡ Quick win

Worth a short comment on why the terminal zero-length phase exists.

The "if last phase ends at period.To with end-grants, append a [To, To] no-op phase" is subtle and pairs tightly with the Inclusive end-boundary path in getGrantRecurrenceTimes. A one-line comment would save a future reader the trip across files. Same goes for the len(phases) == 0 fallback — when can we reach it given the early return on line 60? Worth either documenting it as defensive, or asserting it's unreachable.

📝 Suggested comments
 	if len(phases) > 0 {
 		lastPhase := phases[len(phases)-1]
 		terminalEvent := lastPhase.to.Equal(period.To) &&
 			len(lastPhase.grantsRecurredAtEnd) > 0
 		if terminalEvent {
+			// When a recurrence falls exactly on period.To (Inclusive end boundary),
+			// emit a zero-length terminal phase so the recurrence is applied in this run.
 			phases = append(phases, burnPhase{
 				from: period.To,
 				to:   period.To,
 			})
 		}
 	}
 
 	if len(phases) == 0 {
+		// Defensive: the early-return above should already cover the "no events" case.
 		phases = append(phases, burnPhase{
 			from: period.From,
 			to:   period.To,
 		})
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/burnphase.go` around lines 137 - 154, Add brief
explanatory comments above the terminal zero-length phase append and the
len(phases) == 0 fallback: explain that the zero-length burnPhase (from:
period.To, to: period.To) is intentionally appended when the lastPhase ends at
period.To with grantsRecurredAtEnd to pair with the Inclusive end-boundary
handling in getGrantRecurrenceTimes (so callers treat the end-boundary
recurrence as a no-op phase), and document whether the len(phases) == 0 branch
is defensive or unreachable (or replace it with an explicit assertion) so future
readers of the burnPhase logic (variables lastPhase, terminalEvent, burnPhase
and period.From/period.To) understand the intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/credit/engine/runresult_test.go`:
- Line 231: The test failure messages use "%s" for float64 values causing
unreadable output; update the format verbs in the assert.Equal calls (the ones
comparing res.TotalAvailableGrantAmountAtLastPeriod() with
res.Snapshot.Balance()+res.Snapshot.Usage.Usage-res.Snapshot.Overage and the
similar assertions at the other listed lines) to use a numeric verb such as "%v"
or "%g" for res.Snapshot.Balance(), res.Snapshot.Usage.Usage and
res.Snapshot.Overage so the failure message prints the actual numbers.

---

Nitpick comments:
In `@openmeter/credit/engine/burnphase.go`:
- Around line 137-154: Add brief explanatory comments above the terminal
zero-length phase append and the len(phases) == 0 fallback: explain that the
zero-length burnPhase (from: period.To, to: period.To) is intentionally appended
when the lastPhase ends at period.To with grantsRecurredAtEnd to pair with the
Inclusive end-boundary handling in getGrantRecurrenceTimes (so callers treat the
end-boundary recurrence as a no-op phase), and document whether the len(phases)
== 0 branch is defensive or unreachable (or replace it with an explicit
assertion) so future readers of the burnPhase logic (variables lastPhase,
terminalEvent, burnPhase and period.From/period.To) understand the intent.

In `@openmeter/credit/engine/engine.go`:
- Around line 59-67: Add a one-line comment to
RunResult.TotalAvailableGrantAmountAtLastPeriod explaining that
lo.Last(r.History.ChunkByResets()) intentionally returns the zero value for
empty history so the computation falls back to Snapshot.Balance(); locate the
method TotalAvailableGrantAmountAtLastPeriod on the RunResult type and insert a
concise note above the call to lo.Last indicating the empty-history case is
intentional and expected.

In `@openmeter/credit/engine/grant.go`:
- Around line 65-70: The current getGrantRecurrenceTimes function returns an
inline anonymous slice type ([]struct { time time.Time; grantIDs []string })
which hurts readability and reuse; introduce a small named type (e.g.,
GrantRecurrence or grantRecurrenceTime) in the same package with fields Time
time.Time and GrantIDs []string, replace the anonymous return type in the
getGrantRecurrenceTimes signature and all uses/returns inside that function to
use the new named type, and update any references or tests that expect the old
anonymous shape to compile against the new type name.
- Around line 96-111: The inPeriod closure silently returns false on an unknown
timeutil.Boundary which can hide future bugs; update the default branch in the
inPeriod function (referencing endBoundaryBehavior and the timeutil.Boundary
enum) to surface an explicit error (e.g. panic or log.Fatalf with the unexpected
boundary value) instead of returning false so unknown boundary kinds fail
loudly, and include the boundary value in the message to aid debugging; keep the
existing cases calling period.ContainsInclusive and period.Contains unchanged.

In `@openmeter/credit/engine/history.go`:
- Around line 166-193: In ChunkByResets, avoid over-allocating current.segments
to len(g.segments) for every new chunk: when constructing the initial current
and each reset-created current, set the capacity to the number of remaining
segments instead (e.g., remaining := len(g.segments) - index or similar) so
current.segments is allocated with capacity based on remaining segments; update
the places creating GrantBurnDownHistory with segments to use that remaining
count while keeping the same behavior for usageAtStart and usageAtReset.

In `@openmeter/credit/engine/run.go`:
- Around line 47-89: The loop calls timeline.GetClosedPeriods() multiple times
per iteration (in the range, in the ternary and in the slice length check),
which can be costly and confusing; fix by calling timeline.GetClosedPeriods()
once before the loop (e.g., closed := timeline.GetClosedPeriods()) and iterate
over closed with for idx, period := range closed, then replace other uses
(lo.Ternary idx == len(closed)-1 and similar checks) to reference closed; update
any comments if needed and ensure variables passed to e.runBetweenResets,
inbetweenRunParams, and e.reset remain the same.

In `@openmeter/credit/engine/runresult_test.go`:
- Around line 22-23: In runresult_test.go change the setup assertion that checks
time.Parse from using assert.NoError to require.NoError so the test stops
immediately on parse failure; locate the time.Parse call that assigns t1 and
replace the assert usage with require (you already import require) to prevent
downstream nil/zero-time errors during the test.
- Around line 42-51: Remove the large commented-out grant2 test scaffold: delete
the commented block that defines grant2 (the makeGrant(grant.Grant{...})
snippet) rather than leaving it in the file; if you actually need that extra
test case instead, wire it into the existing test by uncommenting and using the
grant2 variable where appropriate (referencing makeGrant, grant.Grant,
grant.ExpirationPeriod and grant.ExpirationPeriodDurationDay) — otherwise delete
the commented lines to avoid bit-rot.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2d2e728d-271d-46b2-892e-a60e376669c5

📥 Commits

Reviewing files that changed from the base of the PR and between c72f53d and fa8dadf.

📒 Files selected for processing (8)
  • openmeter/credit/engine/burnphase.go
  • openmeter/credit/engine/engine.go
  • openmeter/credit/engine/grant.go
  • openmeter/credit/engine/history.go
  • openmeter/credit/engine/history_test.go
  • openmeter/credit/engine/run.go
  • openmeter/credit/engine/runresult_test.go
  • openmeter/entitlement/metered/balance.go

chrisgacsal
chrisgacsal previously approved these changes May 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
openmeter/credit/engine/runresult_test.go (1)

43-52: 💤 Low value

Dead code or missing scenario? Pick a lane 🛣️

This commented-out grant2 block is identical to grant1, which suggests a multi-grant scenario was planned but never landed (or got abandoned mid-refactor). Either drop it to keep the file tidy, or wire it up as the intended test case — leaving it here gives future readers a small mystery to solve.

🧹 Quick cleanup if it's just leftover
-	// grant2 := makeGrant(grant.Grant{
-	// 	ID:          "grant-2",
-	// 	Amount:      100.0,
-	// 	Priority:    1,
-	// 	EffectiveAt: t1,
-	// 	Expiration: &grant.ExpirationPeriod{
-	// 		Duration: grant.ExpirationPeriodDurationDay,
-	// 		Count:    30,
-	// 	},
-	// })
-

Want me to draft a multi-grant test case (e.g., priority interactions between grant1 and grant2) to exercise TotalAvailableGrantAmountAtLastPeriod more thoroughly?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/credit/engine/runresult_test.go` around lines 43 - 52, The
commented-out grant2 block is dead code; either remove it or turn it into an
active multi-grant test to exercise priority interactions: if you want cleanup,
delete the grant2 commented lines; if you want the multi-grant scenario,
uncomment and create grant2 (ID "grant-2") and add it to the test's grants slice
alongside grant1, then assert behavior of TotalAvailableGrantAmountAtLastPeriod
(or relevant RunResult methods) to validate priority/amount interactions between
grant1 and grant2. Ensure you reference the existing grant creation helper
(makeGrant) and the test assertions that call
TotalAvailableGrantAmountAtLastPeriod so the new grant is actually used.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@openmeter/credit/engine/runresult_test.go`:
- Around line 43-52: The commented-out grant2 block is dead code; either remove
it or turn it into an active multi-grant test to exercise priority interactions:
if you want cleanup, delete the grant2 commented lines; if you want the
multi-grant scenario, uncomment and create grant2 (ID "grant-2") and add it to
the test's grants slice alongside grant1, then assert behavior of
TotalAvailableGrantAmountAtLastPeriod (or relevant RunResult methods) to
validate priority/amount interactions between grant1 and grant2. Ensure you
reference the existing grant creation helper (makeGrant) and the test assertions
that call TotalAvailableGrantAmountAtLastPeriod so the new grant is actually
used.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2b5a167f-349d-40ad-acb5-b358cb735962

📥 Commits

Reviewing files that changed from the base of the PR and between fa8dadf and 7e33ce0.

📒 Files selected for processing (2)
  • openmeter/credit/engine/history_test.go
  • openmeter/credit/engine/runresult_test.go

@GAlexIHU
GAlexIHU merged commit 66c3390 into main May 6, 2026
27 checks passed
@GAlexIHU
GAlexIHU deleted the fix/totalavailablegrant branch May 6, 2026 15:25

This branch was previously deployed

1 inactive deployment
dev — 7e33ce06 Deployed May 6, 2026 by GAlexIHU via Migration Checks #14155
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants