Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(frontend): track draft check staleness by statement content (#20424)

boojack6b21fb45acb6
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index d503fa2f8a..c8cd569bd7 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -1592,6 +1592,7 @@
},
"plan.add-spec": "Add Change",
"plan.add-spec-pending-draft": "Save or discard the pending change before adding another",
+ "plan.checks.completed": "Plan checks completed",
"plan.checks.failed-to-run": "Failed to run plan checks",
"plan.checks.no-check-results": "No check results",
"plan.checks.no-results-match-filters": "No results match your filters",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 6988da3017..f2c9718f55 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -1585,6 +1585,7 @@
},
"plan.add-spec": "Agregar cambio",
"plan.add-spec-pending-draft": "Guarda o descarta el cambio pendiente antes de agregar otro",
+ "plan.checks.completed": "Se completaron las verificaciones del plan",
"plan.checks.failed-to-run": "No se pudieron ejecutar las verificaciones del plan",
"plan.checks.no-check-results": "No hay resultados de verificación",
"plan.checks.no-results-match-filters": "No hay resultados que coincidan con los filtros",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index b3de5e343f..e8aeae9c3b 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -1585,6 +1585,7 @@
},
"plan.add-spec": "変更を追加",
"plan.add-spec-pending-draft": "新しい変更を追加する前に、保留中の変更を保存または破棄してください",
+ "plan.checks.completed": "プランチェックが完了しました",
"plan.checks.failed-to-run": "プランチェックの実行に失敗しました",
"plan.checks.no-check-results": "チェック結果はありません",
"plan.checks.no-results-match-filters": "フィルターに一致する結果はありません",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 0fc1b9d177..a411243e54 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -1585,6 +1585,7 @@
},
"plan.add-spec": "Thêm thay đổi",
"plan.add-spec-pending-draft": "Lưu hoặc hủy thay đổi đang chờ trước khi thêm thay đổi khác",
+ "plan.checks.completed": "Đã hoàn thành kiểm tra kế hoạch",
"plan.checks.failed-to-run": "Không thể chạy kiểm tra kế hoạch",
"plan.checks.no-check-results": "Không có kết quả kiểm tra",
"plan.checks.no-results-match-filters": "Không có kết quả khớp với bộ lọc",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 6ec309f2c6..1a0d78a7b2 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -1585,6 +1585,7 @@
},
"plan.add-spec": "添加变更",
"plan.add-spec-pending-draft": "请先保存或放弃当前的待处理变更,然后再添加新变更",
+ "plan.checks.completed": "已完成计划检查",
"plan.checks.failed-to-run": "运行计划检查失败",
"plan.checks.no-check-results": "暂无检查结果",
"plan.checks.no-results-match-filters": "没有符合筛选条件的结果",
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
index c794261199..93e76ae161 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
@@ -281,6 +281,19 @@ vi.mock("../utils/localSheet", () => ({
return sheet;
},
getNextLocalSheetUID: () => "-1",
+ getSpecStatementContent: (spec: {
+ config?: { case?: string; value?: { sheet?: string } };
+ }) => {
+ if (spec.config?.case !== "changeDatabaseConfig") return undefined;
+ const sheetName = spec.config.value?.sheet;
+ const sheet = sheetName ? mocks.localSheets.get(sheetName) : undefined;
+ return sheet?.content;
+ },
+ isSameStatementContent: (a?: Uint8Array, b?: Uint8Array) => {
+ if (a === b) return true;
+ if (!a || !b || a.length !== b.length) return false;
+ return a.every((byte, index) => byte === b[index]);
+ },
removeLocalSheet: vi.fn(),
}));
@@ -318,20 +331,32 @@ vi.mock("./PlanDetailDraftChecks", () => ({
}: {
checkResults?: CheckReleaseResponse_CheckResult[];
onCheckResultsChange: (
+ content: Uint8Array | undefined,
results: CheckReleaseResponse_CheckResult[] | undefined
) => void;
- selectedSpec: { id: string };
+ selectedSpec: {
+ config?: { case?: string; value?: { sheet?: string } };
+ id: string;
+ };
}) => {
return (
<button
- onClick={() =>
- onCheckResultsChange([
+ onClick={() => {
+ const sheetName =
+ selectedSpec.config?.case === "changeDatabaseConfig"
+ ? selectedSpec.config.value?.sheet
+ : undefined;
+ const sheet = sheetName
+ ? mocks.localSheets.get(sheetName)
+ : undefined;
+ const results = [
{
advices: [],
target: `check-run-for-${selectedSpec.id}`,
} as unknown as CheckReleaseResponse_CheckResult,
- ])
- }
+ ];
+ onCheckResultsChange(sheet?.content, results);
+ }}
>
run draft checks
</button>
@@ -709,6 +734,173 @@ describe("PlanDetailChangesBranch", () => {
expect(container.textContent).not.toContain("spec-2:check-run-for-spec-1");
});
+ it("keeps hook order stable when the selected spec appears after an empty render", async () => {
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => undefined);
+ const emptyPage = buildPageState();
+ emptyPage.plan.specs =
+ [] as unknown as PlanDetailPageState["plan"]["specs"];
+ const page = buildPageState();
+
+ try {
+ act(() => {
+ root.render(
+ <PlanDetailProvider value={emptyPage}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-1"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ });
+ await flush();
+
+ expect(container.textContent).toContain("common.no-data");
+
+ act(() => {
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-1"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ });
+ await flush();
+ } finally {
+ consoleError.mockRestore();
+ }
+
+ expect(
+ consoleError.mock.calls.some((call) =>
+ String(call[0]).includes(
+ "React has detected a change in the order of Hooks"
+ )
+ )
+ ).toBe(false);
+ });
+
+ it("hides stale draft check runs after the create-plan statement changes", async () => {
+ const sheetName = "projects/foo/sheets/-1";
+ mocks.localSheets.set(sheetName, {
+ name: sheetName,
+ content: new TextEncoder().encode("select 1;"),
+ contentSize: 0n,
+ });
+ const page = buildPageState();
+ page.plan.specs = [
+ {
+ id: "spec-1",
+ config: {
+ case: "changeDatabaseConfig",
+ value: {
+ sheet: sheetName,
+ targets: [],
+ },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+
+ const render = () => {
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-1"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ };
+
+ act(render);
+ await flush();
+
+ await act(async () => {
+ (
+ [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "run draft checks"
+ ) as HTMLButtonElement
+ ).click();
+ });
+ await flush();
+
+ expect(container.textContent).toContain("spec-1:check-run-for-spec-1");
+
+ mocks.localSheets.set(sheetName, {
+ name: sheetName,
+ content: new TextEncoder().encode("create table t(id int);"),
+ contentSize: 0n,
+ });
+
+ act(render);
+ await flush();
+
+ expect(container.textContent).toContain("spec-1::0");
+ expect(container.textContent).not.toContain("check-run-for-spec-1");
+ });
+
+ it("keeps draft check runs when the statement is reverted to the checked text", async () => {
+ const sheetName = "projects/foo/sheets/-1";
+ mocks.localSheets.set(sheetName, {
+ name: sheetName,
+ content: new TextEncoder().encode("select 1;"),
+ contentSize: 0n,
+ });
+ const page = buildPageState();
+ page.plan.specs = [
+ {
+ id: "spec-1",
+ config: {
+ case: "changeDatabaseConfig",
+ value: {
+ sheet: sheetName,
+ targets: [],
+ },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+
+ const render = () => {
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-1"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ };
+
+ act(render);
+ await flush();
+
+ await act(async () => {
+ (
+ [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "run draft checks"
+ ) as HTMLButtonElement
+ ).click();
+ });
+ await flush();
+
+ expect(container.textContent).toContain("spec-1:check-run-for-spec-1");
+
+ // Reverting to the same text mints a fresh Uint8Array (new reference) with
+ // identical bytes; the prior checks are still valid, so they must stay.
+ mocks.localSheets.set(sheetName, {
+ name: sheetName,
+ content: new TextEncoder().encode("select 1;"),
+ contentSize: 0n,
+ });
+
+ act(render);
+ await flush();
+
+ expect(container.textContent).toContain("spec-1:check-run-for-spec-1");
+ });
+
it("refreshes the statement section after changing create-plan options", async () => {
mocks.getPlanOptionVisibility.mockReturnValue({
shouldShow: true,
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
index 3501b085b3..ff302b77b4 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -89,7 +89,6 @@ import {
Plan_ChangeDatabaseConfigSchema,
type Plan_Spec,
Plan_SpecSchema,
- type PlanCheckRun,
PlanSchema,
UpdatePlanRequestSchema,
} from "@/types/proto-es/v1/plan_service_pb";
@@ -118,7 +117,12 @@ import {
updateRoleSetter,
updateTransactionMode,
} from "../utils/directiveUtils";
-import { getLocalSheetByName, getNextLocalSheetUID } from "../utils/localSheet";
+import {
+ getLocalSheetByName,
+ getNextLocalSheetUID,
+ getSpecStatementContent,
+ isSameStatementContent,
+} from "../utils/localSheet";
import {
allowGhostForDatabase,
getPlanOptionVisibility,
@@ -164,6 +168,11 @@ type IsolationLevel =
| "REPEATABLE_READ"
| "SERIALIZABLE";
+type DraftCheckResultState = {
+ results: CheckReleaseResponse_CheckResult[];
+ content: Uint8Array | undefined;
+};
+
const BACKUP_AVAILABLE_ENGINES = [
Engine.MYSQL,
Engine.MARIADB,
@@ -203,11 +212,8 @@ export function PlanDetailChangesBranch({
// selectedSpecId (which mirrors the URL) so a draft can be selected even
// when the URL still points at a real spec.
const [isPendingSelected, setIsPendingSelected] = useState(false);
- const [draftCheckRunsBySpecId, setDraftCheckRunsBySpecId] = useState<
- Record<string, PlanCheckRun[]>
- >({});
const [draftCheckResultsBySpecId, setDraftCheckResultsBySpecId] = useState<
- Record<string, CheckReleaseResponse_CheckResult[] | undefined>
+ Record<string, DraftCheckResultState | undefined>
>({});
const [statementVersionBySpecId, setStatementVersionBySpecId] = useState<
Record<string, number>
@@ -454,20 +460,25 @@ export function PlanDetailChangesBranch({
const selectedSpecIdForDraftChecks = selectedSpec?.id;
const handleDraftCheckResultsChange = useCallback(
- (results: CheckReleaseResponse_CheckResult[] | undefined) => {
+ (
+ content: Uint8Array | undefined,
+ results: CheckReleaseResponse_CheckResult[] | undefined
+ ) => {
if (!selectedSpecIdForDraftChecks) return;
setDraftCheckResultsBySpecId((prev) => {
- if (prev[selectedSpecIdForDraftChecks] === results) return prev;
+ const nextState = results ? { results, content } : undefined;
+ const previousState = prev[selectedSpecIdForDraftChecks];
+ if (
+ previousState?.content === nextState?.content &&
+ previousState?.results === nextState?.results
+ ) {
+ return prev;
+ }
return {
...prev,
- [selectedSpecIdForDraftChecks]: results,
+ [selectedSpecIdForDraftChecks]: nextState,
};
});
- setDraftCheckRunsBySpecId((prev) => ({
- ...prev,
- [selectedSpecIdForDraftChecks]:
- transformReleaseCheckResultsToPlanCheckRuns(results ?? []),
- }));
},
[selectedSpecIdForDraftChecks]
);
@@ -477,6 +488,26 @@ export function PlanDetailChangesBranch({
[specId]: (prev[specId] ?? 0) + 1,
}));
}, []);
+ const draftContent =
+ selectedSpec && page.isCreating
+ ? getSpecStatementContent(selectedSpec)
+ : undefined;
+ const draftCheckState = selectedSpec
+ ? draftCheckResultsBySpecId[selectedSpec.id]
+ : undefined;
+ // Memoized on the two content references so the byte fallback only runs when
+ // one of them actually changes (an edit), not on every render.
+ const draftCheckResults = useMemo(
+ () =>
+ isSameStatementContent(draftCheckState?.content, draftContent)
+ ? draftCheckState?.results
+ : undefined,
+ [draftCheckState, draftContent]
+ );
+ const draftCheckRuns = useMemo(
+ () => transformReleaseCheckResultsToPlanCheckRuns(draftCheckResults ?? []),
+ [draftCheckResults]
+ );
if (!selectedSpec) {
return (
@@ -592,7 +623,7 @@ export function PlanDetailChangesBranch({
<PlanDetailStatementSection
planCheckRuns={
page.isCreating
- ? (draftCheckRunsBySpecId[selectedSpec.id] ?? [])
+ ? draftCheckRuns
: planCheckRunListForSpec(page.planCheckRuns, selectedSpec)
}
spec={selectedSpec}
@@ -603,7 +634,7 @@ export function PlanDetailChangesBranch({
selectedSpec.config.case === "changeDatabaseConfig" && (
<PlanDetailDraftChecks
key={selectedSpec.id}
- checkResults={draftCheckResultsBySpecId[selectedSpec.id]}
+ checkResults={draftCheckResults}
onCheckResultsChange={handleDraftCheckResultsChange}
selectedSpec={selectedSpec}
/>
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
index f76b9a40f7..27b2d69275 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
@@ -13,9 +13,8 @@ import {
Release_Type,
} from "@/types/proto-es/v1/release_service_pb";
import { extractProjectResourceName } from "@/utils";
-import { getSheetStatement } from "@/utils/v1/sheet";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
-import { getLocalSheetByName } from "../utils/localSheet";
+import { getSpecStatementContent } from "../utils/localSheet";
import { transformReleaseCheckResultsToPlanCheckRuns } from "../utils/planCheck";
import { PlanTargetDisplay } from "./PlanTargetDisplay";
@@ -26,6 +25,7 @@ export function PlanDetailDraftChecks({
}: {
checkResults?: CheckReleaseResponse_CheckResult[];
onCheckResultsChange: (
+ content: Uint8Array | undefined,
results: CheckReleaseResponse_CheckResult[] | undefined
) => void;
selectedSpec: Plan_Spec;
@@ -34,11 +34,12 @@ export function PlanDetailDraftChecks({
const page = usePlanDetailContext();
const [isRunningChecks, setIsRunningChecks] = useState(false);
- const statement = useMemo(() => {
- if (selectedSpec.config.case !== "changeDatabaseConfig") return "";
- const sheet = getLocalSheetByName(selectedSpec.config.value.sheet);
- return getSheetStatement(sheet);
- }, [selectedSpec]);
+ // content is already the UTF-8 statement bytes, so we send it as-is and use
+ // its reference as the staleness signature — no decode/re-encode roundtrip.
+ const content = useMemo(
+ () => getSpecStatementContent(selectedSpec),
+ [selectedSpec]
+ );
const formattedCheckRuns = useMemo(
() => transformReleaseCheckResultsToPlanCheckRuns(checkResults ?? []),
@@ -63,18 +64,18 @@ export function PlanDetailDraftChecks({
files: [
{
version: "0",
- statement: new TextEncoder().encode(statement),
+ statement: content ?? new Uint8Array(),
},
],
},
targets: selectedSpec.config.value.targets ?? [],
})
);
- onCheckResultsChange(response.results || []);
+ onCheckResultsChange(content, response.results || []);
pushNotification({
module: "bytebase",
style: "SUCCESS",
- title: t("plan.checks.started"),
+ title: t("plan.checks.completed"),
});
} catch (error) {
pushNotification({
@@ -108,7 +109,7 @@ export function PlanDetailDraftChecks({
renderTarget={(target) => (
<PlanTargetDisplay showEnvironment target={target} />
)}
- runDisabled={statement.length === 0}
+ runDisabled={(content?.length ?? 0) === 0}
trailingSummary={trailingSummary}
/>
);
diff --git a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts b/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts
index 74ddd251eb..cea6b28ba8 100644
--- a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts
+++ b/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts
@@ -1,4 +1,5 @@
import { create } from "@bufbuild/protobuf";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";
@@ -32,3 +33,32 @@ export const getLocalSheetByName = (name: string): Sheet => {
export const removeLocalSheet = (name: string): void => {
localSheetsByName.delete(name);
};
+
+// Returns the raw statement bytes of a change-database spec's local sheet.
+// setSheetStatement replaces `content` with a fresh Uint8Array on every edit,
+// so the reference doubles as a cheap change signature: comparing references
+// detects edits in O(1) without decoding the (possibly huge) blob. Both the
+// parent staleness gate and the draft-check runner read it through here.
+export const getSpecStatementContent = (
+ spec: Plan_Spec
+): Uint8Array | undefined => {
+ if (spec.config.case !== "changeDatabaseConfig") return undefined;
+ return getLocalSheetByName(spec.config.value.sheet).content;
+};
+
+// Byte-equality for statement content. The reference check is the O(1) fast
+// path for the common "unchanged since checks ran" case; the byte fallback
+// covers edit-then-revert, where setSheetStatement minted a fresh Uint8Array
+// with identical bytes — the prior checks are still valid for that statement,
+// so a reference mismatch alone must not hide them.
+export const isSameStatementContent = (
+ a: Uint8Array | undefined,
+ b: Uint8Array | undefined
+): boolean => {
+ if (a === b) return true;
+ if (!a || !b || a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+};