Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(plan): converge lifecycle polling after approval (#20900)
boojack7ad7d6eb9f51
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.tsindex 9bdb2b88fa..5a08e890b1 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts@@ -148,6 +148,15 @@ describe("resolvePlanLifecycleHeaderState — pre-deploy gates", () => {"preparing-rollout");});++ test("done issue with approved gates and no loaded rollout -> preparing-rollout", () => {+ expect(+ resolve({+ issueStatus: IssueStatus.DONE,+ approvalStatus: ApprovalStatus.APPROVED,+ }).kind+ ).toBe("preparing-rollout");+ });});describe("resolvePlanLifecycleHeaderState — deploy", () => {diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.tsindex cf7fc8593c..1142ad3bc6 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts@@ -125,15 +125,6 @@ export function resolvePlanLifecycleHeaderState(return { kind: "ready-for-review" };}- // Issue exists but is no longer open (review canceled) and never produced a- // rollout: the lifecycle ended.- if (- input.issueStatus !== undefined &&- input.issueStatus !== IssueStatus.OPEN- ) {- return { kind: "closed" };- }-// Approval flow still being generated — no safe action until it resolves.if (input.approvalStatus === ApprovalStatus.CHECKING) {return { kind: "review-generating" };diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.tsnew file mode 100644index 0000000000..721e1b63dc--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.ts@@ -0,0 +1,114 @@+import { create } from "@bufbuild/protobuf";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { IssueSchema, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import {+ PlanCheckRunSchema,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import {+ RolloutSchema,+ TaskRunSchema,+} from "@/types/proto-es/v1/rollout_service_pb";+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";++const mocks = vi.hoisted(() => ({+ getCurrentUser: vi.fn(),+ getIssue: vi.fn(),+ getPlan: vi.fn(),+ getPlanCheckRun: vi.fn(),+ getProject: vi.fn(),+ getRollout: vi.fn(),+ listTaskRuns: vi.fn(),+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: { getIssue: mocks.getIssue },+ planServiceClientConnect: {+ getPlan: mocks.getPlan,+ getPlanCheckRun: mocks.getPlanCheckRun,+ },+ projectServiceClientConnect: { getProject: mocks.getProject },+ rolloutServiceClientConnect: {+ getRollout: mocks.getRollout,+ listTaskRuns: mocks.listTaskRuns,+ },+ userServiceClientConnect: { getCurrentUser: mocks.getCurrentUser },+}));++import { fetchPlanSnapshot } from "./fetchPlanSnapshot";++const plan = (hasRollout: boolean) =>+ create(PlanSchema, {+ name: "projects/foo/plans/1",+ issue: "projects/foo/issues/1",+ hasRollout,+ });++describe("fetchPlanSnapshot", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getProject.mockResolvedValue(+ create(ProjectSchema, { name: "projects/foo", title: "Foo" })+ );+ mocks.getCurrentUser.mockResolvedValue(+ create(UserSchema, { name: "users/[email protected]" })+ );+ mocks.getPlan.mockResolvedValue(plan(true));+ mocks.getIssue.mockResolvedValue(+ create(IssueSchema, {+ name: "projects/foo/issues/1",+ status: IssueStatus.DONE,+ })+ );+ mocks.getPlanCheckRun.mockResolvedValue(create(PlanCheckRunSchema));+ mocks.getRollout.mockResolvedValue(+ create(RolloutSchema, { name: "projects/foo/rollouts/1" })+ );+ mocks.listTaskRuns.mockResolvedValue({+ taskRuns: [create(TaskRunSchema, { name: "taskRuns/1" })],+ });+ });++ test("reconciles a plan fetched before rollout creation with a done issue", async () => {+ mocks.getPlan+ .mockResolvedValueOnce(plan(false))+ .mockResolvedValueOnce(plan(true));++ const patch = await fetchPlanSnapshot("foo", "1");++ expect(mocks.getPlan).toHaveBeenCalledTimes(2);+ expect(mocks.getRollout).toHaveBeenCalledTimes(1);+ expect(patch.plan.hasRollout).toBe(true);+ expect(patch.rollout?.name).toBe("projects/foo/rollouts/1");+ expect(patch.taskRuns).toHaveLength(1);+ });++ test("keeps rollout and task runs out of the patch when either fetch fails", async () => {+ mocks.listTaskRuns.mockRejectedValue(new Error("temporary failure"));++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect("rollout" in patch).toBe(false);+ expect("taskRuns" in patch).toBe(false);+ });++ test("does not publish stale rollout absence when reconciliation fails", async () => {+ mocks.getPlan+ .mockResolvedValueOnce(plan(false))+ .mockRejectedValueOnce(new Error("temporary failure"));++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect("rollout" in patch).toBe(false);+ expect("taskRuns" in patch).toBe(false);+ });++ test("keeps an issue fetch failure out of the patch", async () => {+ mocks.getIssue.mockRejectedValue(new Error("temporary failure"));++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect("issue" in patch).toBe(false);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.tsindex fd9f1d36d4..986b5dd377 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts@@ -11,6 +11,7 @@ import { silentContextKey } from "@/connect/context-key";import {GetIssueRequestSchema,type Issue,+ IssueStatus,} from "@/types/proto-es/v1/issue_service_pb";import {GetPlanCheckRunRequestSchema,@@ -41,15 +42,15 @@ export interface PlanDetailFetchPatch {projectCanCreateRollout: boolean;projectRequireIssueApproval: boolean;projectRequirePlanCheckNoError: boolean;- issue: Issue | undefined;- rollout: Rollout | undefined;- planCheckRuns: PlanCheckRun[];- taskRuns: TaskRun[];+ issue?: Issue | undefined;+ rollout?: Rollout | undefined;+ planCheckRuns?: PlanCheckRun[];+ taskRuns?: TaskRun[];}-// The rollout and its task-run listing are fetched by both the full page-// snapshot and the slim status lane; only their error handling differs. Keep the-// request shape — schema, silent context, task-run parent glob — in one place.+// Keep the rollout and task-run request shape in one place. They are applied as+// one consistency group below: if either request fails, neither field is+// patched, so a transient poll failure cannot erase last-known-good deploy data.// Fetched WITHOUT touching the store here; the caller (patchState) seeds the// store cache after its staleness guard, so a stale in-flight poll can't// overwrite the shared cache the log viewer reads.@@ -69,6 +70,14 @@ const requestRolloutTaskRuns = (rolloutName: string) =>).then((response) => response.taskRuns);+const requestRolloutState = async (rolloutName: string) => {+ const [rollout, taskRuns] = await Promise.all([+ requestRollout(rolloutName),+ requestRolloutTaskRuns(rolloutName),+ ]);+ return { rollout, taskRuns };+};+const convertRouteQuery = (query: Record<string, unknown>) => {const kv: Record<string, string> = {};for (const [key, value] of Object.entries(query)) {@@ -141,36 +150,59 @@ export const fetchPlanSnapshot = async (};}- const plan = await planPromise;+ let plan = await planPromise;// The rollout name is derived from the plan name, so task runs can load in// parallel with the rollout instead of being serialized behind it.- const rolloutName = plan.hasRollout ? getRolloutFromPlan(plan.name) : "";- const [issue, planCheckRuns, rollout, taskRuns] = await Promise.all([- plan.issue- ? issueServiceClientConnect- .getIssue(+ let rolloutName = plan.hasRollout ? getRolloutFromPlan(plan.name) : "";+ const [issueResult, planCheckRunsResult, rolloutStateResult] =+ await Promise.allSettled([+ plan.issue+ ? issueServiceClientConnect.getIssue(create(GetIssueRequestSchema, { name: plan.issue }),silentCtx)- .catch(() => undefined)- : Promise.resolve(undefined),- planServiceClientConnect- .getPlanCheckRun(- create(GetPlanCheckRunRequestSchema, {- name: `${plan.name}/planCheckRun`,- }),- silentCtx- )- .then((run) => [run] as PlanCheckRun[])- .catch(() => []),- rolloutName- ? requestRollout(rolloutName).catch(() => undefined)- : Promise.resolve(undefined),- rolloutName- ? requestRolloutTaskRuns(rolloutName).catch(() => [])- : Promise.resolve([] as TaskRun[]),- ]);+ : Promise.resolve(undefined),+ planServiceClientConnect+ .getPlanCheckRun(+ create(GetPlanCheckRunRequestSchema, {+ name: `${plan.name}/planCheckRun`,+ }),+ silentCtx+ )+ .then((run) => [run] as PlanCheckRun[]),+ rolloutName+ ? requestRolloutState(rolloutName)+ : Promise.resolve({ rollout: undefined, taskRuns: [] as TaskRun[] }),+ ]);++ // Rollout creation commits plan.hasRollout before marking the issue DONE. If+ // those two RPCs straddle that commit, refresh the older plan half once so a+ // single page snapshot cannot combine DONE with a pre-rollout plan.+ let rolloutState =+ rolloutStateResult.status === "fulfilled"+ ? rolloutStateResult.value+ : undefined;+ if (+ !plan.hasRollout &&+ issueResult.status === "fulfilled" &&+ issueResult.value?.status === IssueStatus.DONE+ ) {+ // The initial no-rollout result belongs to the stale plan half. Do not+ // publish it if reconciliation itself fails; the caller must retain its+ // last-known-good deploy state and let the next poll retry.+ rolloutState = undefined;+ const refreshedPlan = await planServiceClientConnect+ .getPlan(create(GetPlanRequestSchema, { name: plan.name }), silentCtx)+ .catch(() => undefined);+ if (refreshedPlan?.hasRollout) {+ plan = refreshedPlan;+ rolloutName = getRolloutFromPlan(plan.name);+ rolloutState = await requestRolloutState(rolloutName).catch(+ () => undefined+ );+ }+ }return {currentUser,@@ -183,9 +215,10 @@ export const fetchPlanSnapshot = async (),projectRequireIssueApproval: project.requireIssueApproval,projectRequirePlanCheckNoError: project.requirePlanCheckNoError,- issue,- rollout,- planCheckRuns,- taskRuns,+ ...(issueResult.status === "fulfilled" ? { issue: issueResult.value } : {}),+ ...(planCheckRunsResult.status === "fulfilled"+ ? { planCheckRuns: planCheckRunsResult.value }+ : {}),+ ...(rolloutState ? rolloutState : {}),};};diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsxindex b66ad10a81..64e95c5952 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx@@ -2,7 +2,8 @@ import { create } from "@bufbuild/protobuf";import { renderHook, waitFor } from "@testing-library/react";import { act, type ReactNode } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";-import { State } from "@/types/proto-es/v1/common_pb";+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";import {@@ -582,6 +583,31 @@ describe("usePlanDetailPage", () => {expect(after.taskRuns[1]).toBe(before.taskRuns[1]);});+ test("a partial poll patch keeps last-known-good rollout state", async () => {+ mocks.fetchPlanSnapshot.mockResolvedValue({+ ...buildSnapshotPatch({ planId: "plan-1" }),+ rollout: rolloutWithTask(Task_Status.RUNNING),+ taskRuns: [create(TaskRunSchema, { name: "taskRuns/1" })],+ });++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await waitFor(() => expect(result.current.ready).toBe(true));+ const rollout = result.current.rollout;+ const taskRuns = result.current.taskRuns;++ mocks.fetchPlanSnapshot.mockResolvedValue({ projectTitle: "Refreshed" });+ await act(async () => {+ await result.current.refreshState();+ });++ expect(result.current.projectTitle).toBe("Refreshed");+ expect(result.current.rollout).toBe(rollout);+ expect(result.current.taskRuns).toBe(taskRuns);+ });+const rolloutWithTask = (status: Task_Status) =>create(RolloutSchema, {name: "projects/foo/rollouts/1",@@ -663,6 +689,140 @@ describe("usePlanDetailPage", () => {}});+ test("polls on the active cadence while a done issue waits for its rollout", async () => {+ vi.useFakeTimers();+ try {+ mocks.fetchPlanSnapshot.mockResolvedValue(+ buildSnapshotPatch({+ planId: "plan-1",+ issue: {+ name: "projects/foo/issues/1",+ status: IssueStatus.DONE,+ approvalStatus: ApprovalStatus.APPROVED,+ } as PlanDetailPageSnapshot["issue"],+ })+ );++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.ready).toBe(true);+ mocks.fetchPlanSnapshot.mockClear();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ test("polls on the active cadence when the plan expects a missing rollout", async () => {+ vi.useFakeTimers();+ try {+ const patch = buildSnapshotPatch({ planId: "plan-1" });+ mocks.fetchPlanSnapshot.mockResolvedValue({+ ...patch,+ plan: { ...patch.plan, hasRollout: true },+ });++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.ready).toBe(true);+ mocks.fetchPlanSnapshot.mockClear();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ test.each([+ {+ approvalStatus: ApprovalStatus.APPROVED,+ checkStatusCount: { SUCCESS: 2 },+ expectedCalls: 1,+ name: "approved with passing checks",+ },+ {+ approvalStatus: ApprovalStatus.SKIPPED,+ checkStatusCount: {},+ expectedCalls: 1,+ name: "skipped with no required checks",+ },+ {+ approvalStatus: ApprovalStatus.PENDING,+ checkStatusCount: { SUCCESS: 2 },+ expectedCalls: 0,+ name: "pending approval",+ },+ {+ approvalStatus: ApprovalStatus.APPROVED,+ checkStatusCount: { RUNNING: 1 },+ expectedCalls: 0,+ name: "running checks",+ },+ {+ approvalStatus: ApprovalStatus.APPROVED,+ checkStatusCount: { ERROR: 1 },+ expectedCalls: 0,+ name: "failed checks",+ },+ ])("uses the expected pre-rollout cadence for $name", async ({+ approvalStatus,+ checkStatusCount,+ expectedCalls,+ }) => {+ vi.useFakeTimers();+ try {+ const patch = buildSnapshotPatch({+ planId: "plan-1",+ issue: {+ name: "projects/foo/issues/1",+ status: IssueStatus.OPEN,+ approvalStatus,+ } as PlanDetailPageSnapshot["issue"],+ });+ mocks.fetchPlanSnapshot.mockResolvedValue({+ ...patch,+ plan: {+ ...patch.plan,+ planCheckRunStatusCount: checkStatusCount,+ },+ });++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.ready).toBe(true);+ mocks.fetchPlanSnapshot.mockClear();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(expectedCalls);+ } finally {+ vi.useRealTimers();+ }+ });+test("a stale poll from the previous plan cannot overwrite the new plan", async () => {vi.useFakeTimers();try {diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.tsindex feed96dc27..98e0ff0f50 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts@@ -19,7 +19,7 @@ import {PLAN_DETAIL_PHASE_REVIEW,} from "@/react/router/handles";import { useAppStore } from "@/react/stores/app";-import { State } from "@/types/proto-es/v1/common_pb";+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";import { IssueSchema, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import {PlanCheckRunSchema,@@ -38,6 +38,7 @@ import { setDocumentTitle } from "@/utils";import { isTaskActivelyTransitioning } from "@/utils/v1/issue/rollout";import type { PlanDetailPhase } from "../../shared/stores/types";import { usePlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";+import { getPlanCheckSummary } from "../../utils/phaseSummary";import { fetchPlanSnapshot } from "./fetchPlanSnapshot";import type { PlanDetailPageSnapshot, PlanDetailPageState } from "./types";import { useDerivedPlanState } from "./useDerivedPlanState";@@ -344,14 +345,31 @@ export const usePlanDetailPage = ({syncDefaultActivePhases,]);- const { isPlanDone, hasActiveTasks } = useMemo(() => {+ const { isPlanDone, shouldPollActively } = useMemo(() => {if (!snapshot.rollout) {- return { isPlanDone: false, hasActiveTasks: false };+ const checks = getPlanCheckSummary(snapshot.plan);+ const approvalPassed =+ snapshot.issue?.approvalStatus === ApprovalStatus.APPROVED ||+ snapshot.issue?.approvalStatus === ApprovalStatus.SKIPPED;+ const rolloutExpected =+ snapshot.plan.hasRollout ||+ snapshot.issue?.status === IssueStatus.DONE ||+ (snapshot.issue?.status === IssueStatus.OPEN &&+ approvalPassed &&+ checks.running === 0 &&+ checks.error === 0);+ // Once every gate passes, rollout creation is asynchronous. Keep polling+ // at the active cadence through that gap, as well as when either the plan+ // or issue already proves the rollout committed but its data is missing.+ return {+ isPlanDone: false,+ shouldPollActively: rolloutExpected,+ };}const nowMs = Date.now();let taskCount = 0;let allSettled = true;- let hasActiveTasks = false;+ let shouldPollActively = false;for (const stage of snapshot.rollout.stages) {for (const task of stage.tasks) {taskCount++;@@ -366,12 +384,12 @@ export const usePlanDetailPage = ({// stays on the idle cadence rather than polling every second while it// waits — the idle poll still catches it once the backend starts it.if (isTaskActivelyTransitioning(task, nowMs)) {- hasActiveTasks = true;+ shouldPollActively = true;}}}- return { isPlanDone: taskCount > 0 && allSettled, hasActiveTasks };- }, [snapshot.rollout]);+ return { isPlanDone: taskCount > 0 && allSettled, shouldPollActively };+ }, [snapshot.issue, snapshot.plan, snapshot.rollout]);// Poll the whole snapshot on a fixed cadence: fast while a task is// transitioning so PENDING -> RUNNING -> DONE surfaces promptly, idle@@ -382,7 +400,7 @@ export const usePlanDetailPage = ({// result at once, and the cadence tightens as soon as that status is active.usePolling(snapshot.ready && !snapshot.isCreating && !isPlanDone,- hasActiveTasks ? ACTIVE_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS,+ shouldPollActively ? ACTIVE_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS,fetchState);