Repository navigation
fix: totalAvailableGrantAmount - #4304
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesRecurrence Boundary-Aware Phase Planning
Grant Availability & History Tracking
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (8)
openmeter/credit/engine/engine.go (1)
59-67: 💤 Low valueNice clean implementation — small heads-up on the empty-history path.
lo.Lastreturns the zero value whenChunkByResets()is empty (e.g. a run with no segments at all), so this method falls back to0 + 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 missedokcheck.📝 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 valueTiny test ergonomics: prefer
require.NoErrorfor setup that can't recover.
time.Parsefailing here would invalidate the entire test, butassert.NoErrorlets execution continue and you'd hit a nil/zero-time fallout further down. Swapping torequire.NoError(you already importrequire) 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 valueDrop the commented-out
grant2block 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 valueLooks 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
currentover-allocates capacity tolen(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 winCache
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. IfGetClosedPeriods()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 valueTiny 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 valueHeads up: silent fallthrough on unknown Boundary values.
The
defaultbranch ininPeriodreturnsfalse, so if a newtimeutil.Boundarykind ever shows up the recurrence times at the boundary would be silently dropped instead of surfacing as a clear error. SinceBoundaryis 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 winWorth 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 theInclusiveend-boundary path ingetGrantRecurrenceTimes. A one-line comment would save a future reader the trip across files. Same goes for thelen(phases) == 0fallback — 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
📒 Files selected for processing (8)
openmeter/credit/engine/burnphase.goopenmeter/credit/engine/engine.goopenmeter/credit/engine/grant.goopenmeter/credit/engine/history.goopenmeter/credit/engine/history_test.goopenmeter/credit/engine/run.goopenmeter/credit/engine/runresult_test.goopenmeter/entitlement/metered/balance.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/credit/engine/runresult_test.go (1)
43-52: 💤 Low valueDead code or missing scenario? Pick a lane 🛣️
This commented-out
grant2block is identical togrant1, 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
grant1andgrant2) to exerciseTotalAvailableGrantAmountAtLastPeriodmore 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
📒 Files selected for processing (2)
openmeter/credit/engine/history_test.goopenmeter/credit/engine/runresult_test.go
Overview
Fixes #(issue)
Notes for reviewer
Summary by CodeRabbit
New Features
Bug Fixes
Tests