fix: fixes calendar_aligned migration and UI for VK - #3452
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughSummary by CodeRabbit
WalkthroughCalendar alignment was moved from per-rate-limit storage into a virtual-key–level property: legacy DB columns are dropped, the rate-limit model field was removed, virtual-key updates carry ChangesCalendar Alignment Refactor
sequenceDiagram
participant UI as Client (UI)
participant API as Server (API)
participant DB as Database
participant GS as GovernanceStore (in-memory)
rect rgba(0,128,0,0.5)
UI->>API: Submit VK update (includes calendar_aligned)
API->>DB: UpdateVirtualKey (persist calendar_aligned)
DB-->>API: OK
API-->>UI: Response
end
rect rgba(0,0,255,0.5)
Note over GS,DB: Runtime reset resolution (periodic / on-start)
GS->>DB: Read cached VKs and rate-limits
DB-->>GS: VKs, rate-limits
GS->>GS: Build rateLimitID -> VK.calendar_aligned map
GS->>GS: resolvePeriodStart(rateLimit, calendarAlignedFromMap)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested reviewers
Poem
🚥 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)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (2.12.2)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies" Comment |
This stack of pull requests is managed by Graphite. Learn more about stacking. |
Confidence Score: 4/5Safe to merge once the non-deterministic calendar-alignment behavior for shared rate limits is resolved. The migration and DB-layer changes are clean and correct. The main open question is in plugins/governance/store.go — the reverse-map building logic in Important Files Changed
Reviews (7): Last reviewed commit: "fix: fixes calendar_aligned migration an..." | Re-trigger Greptile |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@framework/configstore/migrations.go`:
- Around line 7546-7552: The migration currently swallows DDL errors by logging
warnings when executing tx.Exec for "ALTER TABLE governance_budgets DROP COLUMN
IF EXISTS calendar_aligned" and "ALTER TABLE governance_rate_limits DROP COLUMN
IF EXISTS calendar_aligned"; change this so that any non-nil error from tx.Exec
is returned (or aggregated and returned) so the migration fails instead of
succeeding silently—i.e., in the migration function that calls tx.Exec(...) for
those ALTER TABLE statements, remove the log.Printf warning-only branches and
propagate the error (return err or wrap both errors) so the migration
transaction aborts and the failure is recorded.
In `@plugins/governance/store.go`:
- Around line 1461-1473: The loop that builds rateLimitCalendarAligned from
gs.virtualKeys currently overwrites entries non-deterministically because
sync.Map.Range order is undefined; change the logic in the iteration (the block
that inspects TableVirtualKey.RateLimitID and each
ProviderConfigs[i].RateLimitID) to check for an existing entry before writing
and handle conflicts deterministically: if the ID is not present, set
rateLimitCalendarAligned[id] = vk.CalendarAligned; if it is present and the
existing value differs, record or surface the conflict (e.g., log an error
and/or return a construction error) instead of overwriting so the behavior is
deterministic and invariant violations are detected; apply the same check for
both vk.RateLimitID and each provider-config RateLimitID and add tests verifying
conflicting CalendarAligned values are handled.
In `@ui/app/workspace/virtual-keys/views/virtualKeySheet.tsx`:
- Around line 303-307: The calendar_aligned toggle is shown for alignable rate
limits (hasAnyAlignableRateLimit / showCalendarAlignToggle) but onSubmit only
persists calendar_aligned in the budget branch, so toggles on rate-limit-only
VKs get lost; update the onSubmit handler to always include calendar_aligned in
the payload when the toggle is visible (i.e., when showCalendarAlignToggle or
hasAnyAlignableRateLimit is true), not just when budgets exist, and ensure you
read the value from the same form state used to render the toggle
(calendar_aligned form field) so changes to watchedTokenMaxLimit /
watchedRequestMaxLimit and their reset durations (watchedTokenResetDuration,
watchedRequestResetDuration) are respected.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0e5a49a8-5fd6-422a-a525-f3294cd10a45
📒 Files selected for processing (5)
framework/configstore/migrations.goframework/configstore/rdb.goframework/configstore/tables/ratelimit.goplugins/governance/store.goui/app/workspace/virtual-keys/views/virtualKeySheet.tsx
💤 Files with no reviewable changes (1)
- framework/configstore/tables/ratelimit.go
63802ac to
b9d05f4
Compare
a47983d to
4385224
Compare
b9d05f4 to
d68f3c9
Compare
b5ec099 to
40a5c8b
Compare
d68f3c9 to
f67bf9d
Compare
cb1e4c7 to
9ad2018
Compare
8b8b439 to
23d3ccd
Compare
9ad2018 to
782052b
Compare
23d3ccd to
256fc09
Compare
782052b to
6b6d59a
Compare
6b6d59a to
81193ef
Compare
256fc09 to
0f30480
Compare
Merge activity
|
The base branch was changed.
## Summary Calendar alignment (`calendar_aligned`) is now a VK-only setting stored on `governance_virtual_keys`. Previously, `governance_budgets` and `governance_rate_limits` each carried their own `calendar_aligned` column, which led to inconsistencies after schema migrations. This PR removes those legacy columns, derives the alignment value from the owning virtual key at reset time, and extends the UI toggle to cover rate limits in addition to budgets. ## Changes - **DB migration** (`migrationDropLegacyCalendarAlignedColumns`): Drops `calendar_aligned` from `governance_budgets` and `governance_rate_limits` using `DROP COLUMN IF EXISTS` so it is safe to run on any DB state. - **Rate-limit struct** (`TableRateLimit`): Removed the `CalendarAligned` field since the value is now sourced from the owning VK. - **Reset logic** (`ResetExpiredRateLimitsInMemory`): Builds a reverse map from rate-limit ID → owning VK's `CalendarAligned` value at reset time, covering both VK-attached and provider-config-attached rate limits. Rate limits not reachable from any VK remain non-aligned. - **VK update query** (`UpdateVirtualKey`): Replaced `budget_id` with `calendar_aligned` in the `Select` list so the VK-level alignment flag is persisted on update. - **UI** (`virtualKeySheet.tsx`): The calendar alignment toggle and its warning dialog are now shown when any budget **or** rate limit has a calendar-alignable duration. The toggle and dialog were relocated to a shared section below both the budget and rate-limit fields. Warning copy updated to mention both budget and rate-limit usage resets. ## Type of change - [ ] Bug fix - [x] Feature - [x] Refactor - [ ] Documentation - [ ] Chore/CI ## Affected areas - [x] Core (Go) - [ ] Transports (HTTP) - [ ] Providers/Integrations - [x] Plugins - [x] UI (React) - [ ] Docs ## How to test ```sh # Core/Transports go test ./framework/configstore/... ./plugins/governance/... # UI cd ui pnpm i pnpm build ``` 1. Create a virtual key with a rate limit using a daily or longer reset duration. 2. Verify the "Align to calendar cycle" toggle appears in the rate-limit section. 3. Enable calendar alignment, save, and confirm the rate-limit counters reset and snap to the period boundary. 4. Confirm the toggle also appears (and works) when only budgets with alignable durations are configured. 5. Run the migration against a DB that previously ran `migrate_calendar_aligned` and confirm the `calendar_aligned` columns are dropped from `governance_budgets` and `governance_rate_limits` without error. ## Breaking changes - [x] Yes - [ ] No The `calendar_aligned` column is dropped from `governance_budgets` and `governance_rate_limits`. Any code or query that references those columns directly will break. The migration handles existing databases safely via `DROP COLUMN IF EXISTS`. ## Related issues ## Security considerations None. No auth, secrets, or PII are involved. ## Checklist - [ ] I read `docs/contributing/README.md` and followed the guidelines - [ ] I added/updated tests where appropriate - [ ] I updated documentation where needed - [ ] I verified builds succeed (Go and UI) - [ ] I verified the CI pipeline passes locally if applicable
## Summary Calendar alignment (`calendar_aligned`) is now a VK-only setting stored on `governance_virtual_keys`. Previously, `governance_budgets` and `governance_rate_limits` each carried their own `calendar_aligned` column, which led to inconsistencies after schema migrations. This PR removes those legacy columns, derives the alignment value from the owning virtual key at reset time, and extends the UI toggle to cover rate limits in addition to budgets. ## Changes - **DB migration** (`migrationDropLegacyCalendarAlignedColumns`): Drops `calendar_aligned` from `governance_budgets` and `governance_rate_limits` using `DROP COLUMN IF EXISTS` so it is safe to run on any DB state. - **Rate-limit struct** (`TableRateLimit`): Removed the `CalendarAligned` field since the value is now sourced from the owning VK. - **Reset logic** (`ResetExpiredRateLimitsInMemory`): Builds a reverse map from rate-limit ID → owning VK's `CalendarAligned` value at reset time, covering both VK-attached and provider-config-attached rate limits. Rate limits not reachable from any VK remain non-aligned. - **VK update query** (`UpdateVirtualKey`): Replaced `budget_id` with `calendar_aligned` in the `Select` list so the VK-level alignment flag is persisted on update. - **UI** (`virtualKeySheet.tsx`): The calendar alignment toggle and its warning dialog are now shown when any budget **or** rate limit has a calendar-alignable duration. The toggle and dialog were relocated to a shared section below both the budget and rate-limit fields. Warning copy updated to mention both budget and rate-limit usage resets. ## Type of change - [ ] Bug fix - [x] Feature - [x] Refactor - [ ] Documentation - [ ] Chore/CI ## Affected areas - [x] Core (Go) - [ ] Transports (HTTP) - [ ] Providers/Integrations - [x] Plugins - [x] UI (React) - [ ] Docs ## How to test ```sh # Core/Transports go test ./framework/configstore/... ./plugins/governance/... # UI cd ui pnpm i pnpm build ``` 1. Create a virtual key with a rate limit using a daily or longer reset duration. 2. Verify the "Align to calendar cycle" toggle appears in the rate-limit section. 3. Enable calendar alignment, save, and confirm the rate-limit counters reset and snap to the period boundary. 4. Confirm the toggle also appears (and works) when only budgets with alignable durations are configured. 5. Run the migration against a DB that previously ran `migrate_calendar_aligned` and confirm the `calendar_aligned` columns are dropped from `governance_budgets` and `governance_rate_limits` without error. ## Breaking changes - [x] Yes - [ ] No The `calendar_aligned` column is dropped from `governance_budgets` and `governance_rate_limits`. Any code or query that references those columns directly will break. The migration handles existing databases safely via `DROP COLUMN IF EXISTS`. ## Related issues ## Security considerations None. No auth, secrets, or PII are involved. ## Checklist - [ ] I read `docs/contributing/README.md` and followed the guidelines - [ ] I added/updated tests where appropriate - [ ] I updated documentation where needed - [ ] I verified builds succeed (Go and UI) - [ ] I verified the CI pipeline passes locally if applicable

Summary
Calendar alignment (
calendar_aligned) is now a VK-only setting stored ongovernance_virtual_keys. Previously,governance_budgetsandgovernance_rate_limitseach carried their owncalendar_alignedcolumn, which led to inconsistencies after schema migrations. This PR removes those legacy columns, derives the alignment value from the owning virtual key at reset time, and extends the UI toggle to cover rate limits in addition to budgets.Changes
migrationDropLegacyCalendarAlignedColumns): Dropscalendar_alignedfromgovernance_budgetsandgovernance_rate_limitsusingDROP COLUMN IF EXISTSso it is safe to run on any DB state.TableRateLimit): Removed theCalendarAlignedfield since the value is now sourced from the owning VK.ResetExpiredRateLimitsInMemory): Builds a reverse map from rate-limit ID → owning VK'sCalendarAlignedvalue at reset time, covering both VK-attached and provider-config-attached rate limits. Rate limits not reachable from any VK remain non-aligned.UpdateVirtualKey): Replacedbudget_idwithcalendar_alignedin theSelectlist so the VK-level alignment flag is persisted on update.virtualKeySheet.tsx): The calendar alignment toggle and its warning dialog are now shown when any budget or rate limit has a calendar-alignable duration. The toggle and dialog were relocated to a shared section below both the budget and rate-limit fields. Warning copy updated to mention both budget and rate-limit usage resets.Type of change
Affected areas
How to test
migrate_calendar_alignedand confirm thecalendar_alignedcolumns are dropped fromgovernance_budgetsandgovernance_rate_limitswithout error.Breaking changes
The
calendar_alignedcolumn is dropped fromgovernance_budgetsandgovernance_rate_limits. Any code or query that references those columns directly will break. The migration handles existing databases safely viaDROP COLUMN IF EXISTS.Related issues
Security considerations
None. No auth, secrets, or PII are involved.
Checklist
docs/contributing/README.mdand followed the guidelines