Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions framework/configstore/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,9 @@ func triggerMigrations(ctx context.Context, db *gorm.DB) error {
if err := migrationDropAllowDirectKeysColumnDDL(ctx, db); err != nil {
return err
}
if err := migrationDropLegacyCalendarAlignedColumns(ctx, db); err != nil {
return err
}
return nil
}

Expand Down Expand Up @@ -7527,3 +7530,36 @@ func migrationUniqueTeamNames(ctx context.Context, db *gorm.DB) error {
},
})
}

// migrationDropLegacyCalendarAlignedColumns drops the legacy calendar_aligned
// columns from governance_budgets and governance_rate_limits. Calendar
// alignment is now a VK-only setting (governance_virtual_keys.calendar_aligned);
// budget and rate-limit reset logic derives the value from the owning VK at
// reset time. The columns were re-added by migrate_calendar_aligned after
// add_multi_budget_tables dropped governance_budgets.calendar_aligned, so any
// DB that ran both still has them — this migration cleans them up.
func migrationDropLegacyCalendarAlignedColumns(ctx context.Context, db *gorm.DB) error {
m := migrator.New(db, migrator.DefaultOptions, []*migrator.Migration{{
ID: "drop_legacy_calendar_aligned_columns",
Migrate: func(tx *gorm.DB) error {
tx = tx.WithContext(ctx)
mig := tx.Migrator()
if mig.HasColumn(&tables.TableBudget{}, "calendar_aligned") {
if err := mig.DropColumn(&tables.TableBudget{}, "calendar_aligned"); err != nil {
return fmt.Errorf("failed to drop legacy calendar_aligned column from governance_budgets: %w", err)
}
}
if mig.HasColumn(&tables.TableRateLimit{}, "calendar_aligned") {
if err := mig.DropColumn(&tables.TableRateLimit{}, "calendar_aligned"); err != nil {
return fmt.Errorf("failed to drop legacy calendar_aligned column from governance_rate_limits: %w", err)
}
}
return nil
},
Rollback: func(tx *gorm.DB) error { return nil },
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}})
if err := m.Migrate(); err != nil {
return fmt.Errorf("error running drop_legacy_calendar_aligned_columns migration: %s", err.Error())
}
return nil
}
2 changes: 1 addition & 1 deletion framework/configstore/rdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -2457,7 +2457,7 @@ func (s *RDBConfigStore) UpdateVirtualKey(ctx context.Context, virtualKey *table
} else {
virtualKey.ID = existing.ID
if err := txDB.WithContext(ctx).
Select("name", "description", "value", "is_active", "team_id", "customer_id", "budget_id", "rate_limit_id", "config_hash", "updated_at", "encryption_status", "value_hash").
Select("name", "description", "value", "is_active", "team_id", "customer_id", "rate_limit_id", "calendar_aligned", "config_hash", "updated_at", "encryption_status", "value_hash").
Updates(virtualKey).Error; err != nil {
return s.parseGormError(err)
}
Expand Down
2 changes: 0 additions & 2 deletions framework/configstore/tables/budget.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ type TableBudget struct {
VirtualKeyID *string `gorm:"type:varchar(255);index" json:"virtual_key_id,omitempty"`
ProviderConfigID *uint `gorm:"index" json:"provider_config_id,omitempty"`

CalendarAligned bool `gorm:"default:false" json:"calendar_aligned"` // When true, all budgets under this VK reset at clean calendar boundaries

// Config hash is used to detect the changes synced from config.json file
// Every time we sync the config.json file, we will update the config hash
ConfigHash string `gorm:"type:varchar(255);null" json:"config_hash"`
Expand Down
2 changes: 0 additions & 2 deletions framework/configstore/tables/ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ type TableRateLimit struct {
RequestCurrentUsage int64 `gorm:"default:0" json:"request_current_usage"` // Current request usage
RequestLastReset time.Time `gorm:"index" json:"request_last_reset"` // Last time request counter was reset

CalendarAligned bool `gorm:"default:false" json:"calendar_aligned"` // When true, all budgets under this VK reset at clean calendar boundaries

// Config hash is used to detect the changes synced from config.json file
// Every time we sync the config.json file, we will update the config hash
ConfigHash string `gorm:"type:varchar(255);null" json:"config_hash"`
Expand Down
3 changes: 3 additions & 0 deletions framework/configstore/tables/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ type TableTeam struct {
Claims *string `gorm:"type:text" json:"-"`
ParsedClaims map[string]any `gorm:"-" json:"claims"`

// IsBudgetCalendarAligned indicates whether the team's budget is calendar-aligned
CalendarAligned bool `gorm:"-" json:"calendar_aligned"`

// Config hash is used to detect the changes synced from config.json file
// Every time we sync the config.json file, we will update the config hash
ConfigHash string `gorm:"type:varchar(255);null" json:"config_hash"`
Expand Down
35 changes: 32 additions & 3 deletions plugins/governance/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -1373,9 +1373,17 @@ func (gs *LocalGovernanceStore) ResetExpiredBudgetsInMemory(ctx context.Context)
if !ok || budget == nil {
return true
}
// Find if the budget is calendar aligned on the virtualkey attached to this budget
calendarAligned := false
if budget.VirtualKeyID != nil {
virtualKey, ok := gs.virtualKeys.Load(*budget.VirtualKeyID)
if ok {
calendarAligned = virtualKey.(*configstoreTables.TableVirtualKey).CalendarAligned
}
}
var shouldReset bool
var newLastReset time.Time
if budget.CalendarAligned {
if calendarAligned {
currentPeriodStart := configstoreTables.GetCalendarPeriodStart(budget.ResetDuration, now)
if currentPeriodStart.After(budget.LastReset) {
shouldReset = true
Expand Down Expand Up @@ -1446,13 +1454,34 @@ func (gs *LocalGovernanceStore) ResetExpiredRateLimitsInMemory(ctx context.Conte
}
return nil
}
// Build reverse map from rate_limit ID to the owning VK's CalendarAligned
// setting. Rate limits attach to either a VK (vk.RateLimitID) or a provider
// config (pc.RateLimitID) which itself belongs to a VK. Rate limits not
// reachable from any VK (e.g. team-attached) remain non-aligned.
rateLimitCalendarAligned := make(map[string]bool)
gs.virtualKeys.Range(func(_, v any) bool {
vk, ok := v.(*configstoreTables.TableVirtualKey)
if !ok || vk == nil {
return true
}
if vk.RateLimitID != nil {
rateLimitCalendarAligned[*vk.RateLimitID] = vk.CalendarAligned
}
for i := range vk.ProviderConfigs {
if pc := &vk.ProviderConfigs[i]; pc.RateLimitID != nil {
rateLimitCalendarAligned[*pc.RateLimitID] = vk.CalendarAligned
}
Comment thread
roroghost17 marked this conversation as resolved.
Resolved
}
return true
})
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
gs.rateLimits.Range(func(key, value any) bool {
rateLimit, ok := value.(*configstoreTables.TableRateLimit)
if !ok || rateLimit == nil {
return true
}
tokenNewLastReset := resolvePeriodStart(rateLimit.TokenResetDuration, rateLimit.CalendarAligned, rateLimit.TokenLastReset)
requestNewLastReset := resolvePeriodStart(rateLimit.RequestResetDuration, rateLimit.CalendarAligned, rateLimit.RequestLastReset)
calendarAligned := rateLimitCalendarAligned[rateLimit.ID]
tokenNewLastReset := resolvePeriodStart(rateLimit.TokenResetDuration, calendarAligned, rateLimit.TokenLastReset)
requestNewLastReset := resolvePeriodStart(rateLimit.RequestResetDuration, calendarAligned, rateLimit.RequestLastReset)
if tokenNewLastReset == nil && requestNewLastReset == nil {
return true
}
Expand Down
30 changes: 13 additions & 17 deletions transports/bifrost-http/handlers/governance.go
Original file line number Diff line number Diff line change
Expand Up @@ -1551,13 +1551,12 @@ func (h *GovernanceHandler) createTeam(ctx *fasthttp.RequestCtx) {
}
seenDurations[b.ResetDuration] = true
budget := configstoreTables.TableBudget{
ID: uuid.NewString(),
MaxLimit: b.MaxLimit,
ResetDuration: b.ResetDuration,
LastReset: budgetLastReset(b.CalendarAligned, b.ResetDuration),
CurrentUsage: 0,
CalendarAligned: b.CalendarAligned,
TeamID: &team.ID,
ID: uuid.NewString(),
MaxLimit: b.MaxLimit,
ResetDuration: b.ResetDuration,
LastReset: budgetLastReset(b.CalendarAligned, b.ResetDuration),
CurrentUsage: 0,
TeamID: &team.ID,
}
if err := validateBudget(&budget); err != nil {
return err
Expand Down Expand Up @@ -1688,14 +1687,12 @@ func (h *GovernanceHandler) updateTeam(ctx *fasthttp.RequestCtx) {
matchedIDs := make(map[string]bool)
for _, b := range req.Budgets {
if existing, found := existingByDuration[b.ResetDuration]; found {
wasCalendarAligned := existing.CalendarAligned
existing.MaxLimit = b.MaxLimit
existing.CalendarAligned = b.CalendarAligned
// Match the UI's calendar-alignment confirmation promise: on the
// false → true transition, snap LastReset to the current period
// start and zero out CurrentUsage now, instead of lazily waiting
// for the next period boundary in ResetExpiredBudgetsInMemory.
if b.CalendarAligned && !wasCalendarAligned {
if b.CalendarAligned {
existing.LastReset = configstoreTables.GetCalendarPeriodStart(b.ResetDuration, time.Now())
existing.CurrentUsage = 0
}
Expand All @@ -1709,13 +1706,12 @@ func (h *GovernanceHandler) updateTeam(ctx *fasthttp.RequestCtx) {
matchedIDs[existing.ID] = true
} else {
budget := configstoreTables.TableBudget{
ID: uuid.NewString(),
MaxLimit: b.MaxLimit,
ResetDuration: b.ResetDuration,
LastReset: budgetLastReset(b.CalendarAligned, b.ResetDuration),
CurrentUsage: 0,
CalendarAligned: b.CalendarAligned,
TeamID: &team.ID,
ID: uuid.NewString(),
MaxLimit: b.MaxLimit,
ResetDuration: b.ResetDuration,
LastReset: budgetLastReset(b.CalendarAligned, b.ResetDuration),
CurrentUsage: 0,
TeamID: &team.ID,
}
if err := validateBudget(&budget); err != nil {
return err
Expand Down
105 changes: 56 additions & 49 deletions ui/app/workspace/virtual-keys/views/virtualKeySheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -290,13 +290,20 @@ export default function VirtualKeySheet({ virtualKey, teams, customers, defaultT
const watchedBudgets = form.watch("budgets");
const watchedTokenMaxLimit = form.watch("tokenMaxLimit");
const watchedRequestMaxLimit = form.watch("requestMaxLimit");
const watchedTokenResetDuration = form.watch("tokenResetDuration");
const watchedRequestResetDuration = form.watch("requestResetDuration");
const watchedBudgetCalendarAligned = form.watch("budgetCalendarAligned");

// Calendar alignment is VK-wide: show toggle if any budget has a max_limit and supports alignment
// Calendar alignment is VK-wide and applies to both budgets and rate limits: show the
// toggle when any configured budget or rate-limit uses a calendar-alignable duration.
const hasAnyAlignableBudget =
watchedBudgets &&
watchedBudgets.length > 0 &&
watchedBudgets.some((b) => b.max_limit !== undefined && b.max_limit !== null && supportsCalendarAlignment(b.reset_duration || "1M"));
const hasAnyAlignableRateLimit =
(watchedTokenMaxLimit !== undefined && watchedTokenMaxLimit !== null && supportsCalendarAlignment(watchedTokenResetDuration || "1h")) ||
(watchedRequestMaxLimit !== undefined && watchedRequestMaxLimit !== null && supportsCalendarAlignment(watchedRequestResetDuration || "1h"));
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
const showCalendarAlignToggle = hasAnyAlignableBudget || hasAnyAlignableRateLimit;

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Handle adding a new provider configuration
const handleAddProvider = (provider: string) => {
Expand Down Expand Up @@ -1243,54 +1250,6 @@ export default function VirtualKeySheet({ virtualKey, teams, customers, defaultT
showReset={isEditing && !!(virtualKey?.budgets?.length || (watchedBudgets && watchedBudgets.length > 0))}
/>

{/* Calendar alignment toggle — shown when any budget supports alignment */}
{hasAnyAlignableBudget && (
<div className="flex items-center justify-between gap-4 rounded-md border px-3 py-2">
<div className="space-y-0.5">
<Label htmlFor="vk-budget-calendar-aligned-toggle" className="text-sm font-normal">
Align to calendar cycle
</Label>
<p id="vk-budget-calendar-aligned-description" className="text-muted-foreground text-xs">
Reset at the start of each period (e.g. 1st of month) instead of rolling from creation date
</p>
</div>
<Switch
id="vk-budget-calendar-aligned-toggle"
aria-describedby="vk-budget-calendar-aligned-description"
checked={watchedBudgetCalendarAligned}
onCheckedChange={handleCalendarAlignedChange}
data-testid="vk-budget-calendar-aligned-toggle"
/>
</div>
)}

{/* Warning dialog shown when enabling calendar alignment on an existing budget */}
<AlertDialog open={showCalendarAlignWarning} onOpenChange={setShowCalendarAlignWarning}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Reset budget usage?</AlertDialogTitle>
<AlertDialogDescription>
Enabling calendar alignment will reset all budget usage for this virtual key to{" "}
<span className="font-semibold">$0.00</span> and snap each budget&apos;s reset date to the start of its current
period (e.g. start of day, week, month, or year). The usage reset to $0.00 cannot be undone, but calendar
alignment can be turned off later. This will take effect when you save.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel data-testid="vk-calendar-align-cancel-btn">Cancel</AlertDialogCancel>
<AlertDialogAction
data-testid="vk-calendar-align-enable-btn"
onClick={() => {
form.setValue("budgetCalendarAligned", true, { shouldDirty: true });
setShowCalendarAlignWarning(false);
}}
>
Enable Calendar Alignment
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>

{/* Reassign team confirmation dialog */}
<AlertDialog
open={showReassignTeamWarning}
Expand Down Expand Up @@ -1391,6 +1350,54 @@ export default function VirtualKeySheet({ virtualKey, teams, customers, defaultT
)}
/>
</div>
{/* Calendar alignment — VK-wide setting that applies to both budgets and rate limits */}
{showCalendarAlignToggle && (
<div className="flex items-center justify-between gap-4 rounded-md border px-3 py-2">
<div className="space-y-0.5">
<Label htmlFor="vk-budget-calendar-aligned-toggle" className="text-sm font-normal">
Align to calendar cycle
</Label>
<p id="vk-budget-calendar-aligned-description" className="text-muted-foreground text-xs">
Reset budgets and rate limits at the start of each period (e.g. 1st of month) instead of rolling from creation
date. Applies to durations of a day or longer.
</p>
</div>
<Switch
id="vk-budget-calendar-aligned-toggle"
aria-describedby="vk-budget-calendar-aligned-description"
checked={watchedBudgetCalendarAligned}
onCheckedChange={handleCalendarAlignedChange}
data-testid="vk-budget-calendar-aligned-toggle"
/>
</div>
)}

{/* Warning dialog shown when enabling calendar alignment on an existing VK */}
<AlertDialog open={showCalendarAlignWarning} onOpenChange={setShowCalendarAlignWarning}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Reset budget and rate-limit usage?</AlertDialogTitle>
<AlertDialogDescription>
Enabling calendar alignment will reset budget usage to <span className="font-semibold">$0.00</span> and
token/request rate-limit counters to <span className="font-semibold">0</span> for this virtual key, then snap each
reset date to the start of its current period (e.g. start of day, week, month, or year). The usage reset cannot
be undone, but calendar alignment can be turned off later. This will take effect when you save.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel data-testid="vk-calendar-align-cancel-btn">Cancel</AlertDialogCancel>
<AlertDialogAction
data-testid="vk-calendar-align-enable-btn"
onClick={() => {
form.setValue("budgetCalendarAligned", true, { shouldDirty: true });
setShowCalendarAlignWarning(false);
}}
>
Enable Calendar Alignment
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{(teams?.length > 0 || customers?.length > 0) && (
<>
<DottedSeparator className="my-6" />
Expand Down
Loading