Skip to content

fix(api): move expireIfStale async; exempt empty-account rows from scoped drop - #1043

Merged
cristim merged 3 commits into
feat/multicloud-web-frontendfrom
fix/history-get-readonly-scoping
Jun 7, 2026
Merged

cristim merged 3 commits into
feat/multicloud-web-frontendfrom
fix/history-get-readonly-scoping

Conversation

@cristim

@cristim cristim commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #1032

Two coupled defects on the getHistory GET read path:

  1. GET mutates DB (non-idempotent, racy): expireIfStale called TransitionExecutionStatus inline inside fetchExecutionsAsHistory. A pure GET that writes races concurrent loads (two simultaneous requests both attempt the transition; the loser's error is swallowed) and makes HEAD/replay semantics unsafe.

  2. Scoped users lose in-flight financial actions (bug(purchases): approved AWS purchase vanishes from History — 'approved'/'running' execution statuses hidden by the History list (P0) #621 regression): executionToHistoryRow sets AccountID = "" when exec.CloudAccountID is nil and recs carry no common account (ambient/multi-account path). filterPurchaseHistoryByAllowedAccounts then calls MatchesAccount(allowed, "", "") which is false for any scoped non-admin user, silently dropping in-flight executions -- re-introducing the silent-disappearance bug bug(purchases): approved AWS purchase vanishes from History — 'approved'/'running' execution statuses hidden by the History list (P0) #621 fixed.

Changes

Defect 1: Extracted stale-expiry out of the hot fetch loop. The GET now collects stale execution IDs during the read phase and fires TransitionExecutionStatus in a best-effort background goroutine (expireStaleExecutionsAsync) after the response is assembled. The transition remains idempotent via the FROM-status guard in the store. Response reflects current DB state; next History load sees the updated status.

Defect 2: filterPurchaseHistoryByAllowedAccounts now passes rows with empty AccountID through for scoped users. These carry no account-specific data (they are ambient/unattributed executions) so cross-tenant isolation is not affected; the view:purchases gate already fired.

Verification

go build ./..., go vet ./internal/api/..., go test ./internal/api/... -- 1502 tests pass, no race detector issues.

Two new regression tests that fail against pre-fix code:

  • TestHandler_getHistory_GetIsReadOnly: asserts the handler returns before TransitionExecutionStatus completes (gate + channel pattern, no sleep). Pre-fix: handler blocks on the gate (deadlock); test fails with timeout.
  • TestHandler_getHistory_ScopedUserSeesEmptyAccountRows: asserts a scoped user sees ambient-credential executions (AccountID == ""). Pre-fix: row dropped, require.Len fails.

Updated TestHandler_getHistory_ExpireIfStale to assert the new async behaviour: response shows pre-transition status ("pending"); goroutine fires in the background, verified via done channel (no sleep per project memory).

References #621 (original silent-disappearance fix this partially regresses).

Scope expanded

Also closes #1061

Three additional findings from docs/code-review/01-api-handlers.md folded into this PR (FOLD-1043):

  • 01-M1 (parseHistoryFilters limit parsing): fmt.Sscanf silently swallowed non-integer limit values, giving callers no feedback. Replaced with strconv.Atoi + 400 ClientError on parse failure. limit < 1 now clamps to DefaultListLimit (per feedback_strict_int_parse). Regression guard: TestHandler_getHistory_LimitParsing (6 sub-cases, fails pre-fix on the non-integer and float cases).

  • 01-L1 (handler_history.go merge slice): append(completed, extra...) with a //nolint:gocritic comment was replaced by an explicit pre-allocated slice (make + two appends) that is self-documenting and avoids the lint suppression.

  • 01-L2 (history filter site): filterPurchaseHistoryByAllowedAccounts used purchases[:0] as the output slice, aliasing the input's backing array. Replaced with make([]..., 0, len(purchases)) for a true fresh slice.

Additionally, known_issues/32_history_lazy_expire_test.md is removed: the test gap it documented (no test for the async stale-expiry path) is closed by TestHandler_getHistory_ExpireIfStale added in this PR's original commit.

…oped drop (closes #1032)

Two coupled defects on the getHistory GET read path:

1. expireIfStale called TransitionExecutionStatus inline in
   fetchExecutionsAsHistory, making the GET a racy write: concurrent
   loads both attempt the transition and the loser's error is swallowed.
   Fix: collect stale execution IDs during the read phase; fire
   TransitionExecutionStatus in a best-effort background goroutine (via
   expireStaleExecutionsAsync) after the response is assembled. The
   response reflects current DB state; the next History load sees the
   updated status. The transition remains idempotent via the
   FROM-status guard in TransitionExecutionStatus.

2. executionToHistoryRow sets AccountID = "" when exec.CloudAccountID
   is nil and recs carry no common account (ambient/multi-account path).
   filterPurchaseHistoryByAllowedAccounts then calls
   MatchesAccount(allowed, "", "") == false for any scoped user,
   silently dropping in-flight financial actions the user owns -- a
   regression of #621's silent-disappearance fix. Fix: pass rows with
   empty AccountID through the filter unconditionally for scoped users;
   these carry no account-specific data that would violate cross-tenant
   isolation, and the view:purchases gate already fired.

Regression tests added that fail against the pre-fix code:
- TestHandler_getHistory_GetIsReadOnly: asserts the handler returns
  before TransitionExecutionStatus completes (gate/channel pattern).
- TestHandler_getHistory_ScopedUserSeesEmptyAccountRows: asserts a
  scoped user sees ambient-credential executions (AccountID == "").
Updated TestHandler_getHistory_ExpireIfStale to reflect the new
async behaviour: response shows pre-transition status; goroutine fires
in the background, verified via done channel (no sleep).
@cristim cristim added bug Something isn't working triaged Item has been triaged priority/p2 Backlog-worthy severity/high Significant harm urgency/this-sprint Within the current sprint impact/many Affects most users effort/m Days type/bug Defect labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@cristim, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 11 minutes and 52 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8a36d9b8-77c0-45bd-adf3-75173ca780d3

📥 Commits

Reviewing files that changed from the base of the PR and between cbdc4be and 959c757.

📒 Files selected for processing (3)
  • internal/api/handler_history.go
  • internal/api/handler_history_test.go
  • known_issues/32_history_lazy_expire_test.md
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/history-get-readonly-scoping

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

@cristim

cristim commented Jun 7, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

cristim added 2 commits June 7, 2026 04:17
…oses #1061)

Three code-quality fixes in handler_history.go (FOLD-1043, findings
01-M1, 01-L1, 01-L2 history site):

01-M1: parseHistoryFilters now uses strconv.Atoi for the limit query
param and returns a 400 ClientError on parse failure instead of
silently ignoring a bad value via fmt.Sscanf. limit < 1 is clamped to
DefaultListLimit (previously the <= 0 guard covered negatives but not
the zero case explicitly). Aligns with feedback_strict_int_parse.

01-L1: Replace append(completed, extra...) + nolint:gocritic comment
with an explicit pre-allocated slice (make + two appends). The nolint
comment was accurate but obscure; the explicit allocation is self-
documenting and sidesteps the lint concern without a suppression.

01-L2 (history site): filterPurchaseHistoryByAllowedAccounts used
purchases[:0] as the filter output, aliasing the input's backing array.
Replace with make([]..., 0, len(purchases)) for a true fresh slice.

Regression tests added (TestHandler_getHistory_LimitParsing): six
table-driven sub-tests covering non-integer, float, negative, zero,
over-max, and valid limits. Fails pre-fix on the non-integer and float
cases (fmt.Sscanf returns no error and falls back to default silently).
The expireIfStale test gap documented in this file was closed by
TestHandler_getHistory_ExpireIfStale added in the prior commit on this
branch. The placeholder is no longer needed.
@cristim

cristim commented Jun 7, 2026

Copy link
Copy Markdown
Member Author

FOLD-1043 additions (closes #1061)

Three findings from 01-api-handlers.md folded in as two additional commits:

Commit 1 (fix(api): use strconv.Atoi for limit; fresh slice in filter/merge):

  • 01-M1 (parseHistoryFilters limit): replaced fmt.Sscanf + silent-ignore with strconv.Atoi + 400 ClientError on non-integer input. limit < 1 now clamps to DefaultListLimit. Regression guard: TestHandler_getHistory_LimitParsing (6 sub-cases; non-integer/float cases fail pre-fix).
  • 01-L1 (merge slice): replaced append(completed, extra...) //nolint:gocritic with explicit pre-allocation (make + two appends). Self-documenting; no lint suppression needed.
  • 01-L2 (filter fresh slice): replaced purchases[:0] alias with make([]..., 0, len(purchases)) in filterPurchaseHistoryByAllowedAccounts.

Commit 2 (chore(known-issues): remove 32_history_lazy_expire_test.md):

Removes the placeholder that documented the missing stale-expiry test -- the gap is closed by TestHandler_getHistory_ExpireIfStale added in this PR's original commit.

Verification: go build ./..., go vet ./internal/api/..., go test ./internal/api/... -- 1502 tests pass.

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

@cristim Thanks for the detailed summary of the FOLD-1043 additions. The changes look well-scoped:

  • 01-M1: strconv.Atoi + 400 error is the right call — silent fmt.Sscanf failures on malformed limit are a classic footgun, and the 6-subcase regression guard covers the key edge cases (non-integer, float, etc.).
  • 01-L1: Dropping the //nolint:gocritic in favour of an explicit pre-allocated slice is a net improvement in readability and maintainability.
  • 01-L2: Replacing purchases[:0] (aliased backing array) with make([]..., 0, len(purchases)) is a correctness fix — the alias could silently corrupt the input slice under certain call patterns.
  • Commit 2: Removing the now-stale 32_history_lazy_expire_test.md placeholder keeps the known-issues tracking honest.

Triggering an incremental review of the new commits now.


🧠 Learnings used
Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-05-05T15:44:54.463Z
Learning: In the LeanerCloud/CUDly repository, when a CodeRabbit review flags something as "outside-diff" that was already implemented in an earlier commit of the same PR, it is likely a stale-snapshot artifact where the review diff was generated against a pre-fix view. The inline comment convention `(CR pass on PR #<number> Finding N)` is used by the maintainer (cristim) to mark lines that were changed in direct response to a prior CodeRabbit review pass.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-06-06T06:43:53.770Z
Learning: In LeanerCloud/CUDly PR `#995` (issue `#950` ownership gate), the Dashboard "Upcoming purchases" widget (`dashboard.ts`) has two Cancel entry points (card-level and modal) that both call `api.deletePlannedPurchase`. The `UpcomingPurchase` response DTO must include `CreatedByUserID *string` (omitempty, mirroring `PlannedPurchase`) so the frontend can gate these buttons via a `canCancelUpcomingPurchase` helper that mirrors `canManageScheduledPurchase` on the Plans page. Without this, the backend correctly 403s non-owners but the UI has no gate and the UX is broken. Regressions: `frontend/src/__tests__/dashboard-ownership-950.test.ts` (6 tests) and `TestHandler_getUpcomingPurchases_PropagatesCreatedByUserID`. Fixed in commit 94326f6b9.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-06-06T06:43:53.770Z
Learning: In LeanerCloud/CUDly PR `#995` (issue `#950` ownership gate), `POST /api/plans/{id}/purchases` (`createPurchaseExecutionsTx`) must stamp `created_by_user_id` via `resolveCreatorUserID(session)` at creation time. Without this, every scheduled purchase created via the Plans-page "Create planned purchases" action ships a NULL creator, which the ownership gate treats as a legacy row and denies management to all non-`update-any` users — including the creator themselves. The admin API key path must set `CreatedByUserID` to nil (not the key identity). Regressions: `TestHandler_createPlannedPurchases_StampsCreator` and `TestHandler_createPlannedPurchases_AdminAPIKeyCreatorIsNil`. Fixed in commit 9ef1b4352.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-06-06T06:41:06.830Z
Learning: In LeanerCloud/CUDly PR `#804`, the purchase-history revocation migration is numbered 000066 (`000066_purchase_history_revocation.{up,down}.sql`). It was renumbered multiple times due to collisions: 000057 → 000059 → 000060 → 000064 → 000065 → 000066. 000065 is occupied by `000065_enforce_min_one_admin` (merged via `#921`) on the base branch.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-06-06T06:41:06.830Z
Learning: In LeanerCloud/CUDly PR `#804`, `CancelScheduledExecutionAtomic` (`WHERE status = 'scheduled'`) is distinct from `CancelExecutionAtomic` (`WHERE status IN ('pending','notified')`). The pre-fire-delay revoke path uses `CancelScheduledExecutionAtomic`; the 410 "window closed" / 409 "not pending" race outcomes must remain disambiguated. Using `CancelExecutionAtomic` for scheduled-execution revocation is a critical bug (the execution fires and the user is charged while the UI shows "cancelled").
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@cristim
cristim merged commit ee34869 into feat/multicloud-web-frontend Jun 7, 2026
4 checks passed
@cristim
cristim deleted the fix/history-get-readonly-scoping branch June 7, 2026 20:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working effort/m Days impact/many Affects most users priority/p2 Backlog-worthy severity/high Significant harm triaged Item has been triaged type/bug Defect urgency/this-sprint Within the current sprint

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant