Skip to content

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

feat(plan-detail): restore gh-ost parameter configure UI (BYT-9781) (#20669)

boojack8167f1b9160b
diff --git a/backend/component/ghost/manifest_test.go b/backend/component/ghost/manifest_test.go
new file mode 100644
index 0000000000..d5efeb139a
--- /dev/null
+++ b/backend/component/ghost/manifest_test.go
@@ -0,0 +1,68 @@
+package ghost
+
+import (
+ "encoding/json"
+ "os"
+ "strconv"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// frontendFlagManifestPath is the gh-ost flag manifest the "Configure" UI builds
+// its parameter list from (frontend/src/react/components/ghost/constants.ts
+// imports it). The path is relative to this package directory, where `go test`
+// runs.
+const frontendFlagManifestPath = "../../../frontend/src/react/components/ghost/flags.json"
+
+// TestFrontendFlagManifestInSync fails if the frontend gh-ost flag manifest
+// drifts from the backend allowlist/defaults, so a flag added, removed, or
+// re-defaulted on one side cannot silently diverge from the other.
+func TestFrontendFlagManifestInSync(t *testing.T) {
+ data, err := os.ReadFile(frontendFlagManifestPath)
+ require.NoErrorf(t, err, "read frontend flag manifest %s", frontendFlagManifestPath)
+
+ var manifest []struct {
+ Key string `json:"key"`
+ Type string `json:"type"`
+ Default string `json:"default"`
+ }
+ require.NoErrorf(t, json.Unmarshal(data, &manifest), "parse %s", frontendFlagManifestPath)
+
+ // 1. The manifest's key set must match the backend allowlist exactly.
+ manifestKeys := make(map[string]bool, len(manifest))
+ for _, f := range manifest {
+ require.Falsef(t, manifestKeys[f.Key], "duplicate flag %q in manifest", f.Key)
+ manifestKeys[f.Key] = true
+ }
+ for key := range knownKeys {
+ require.Truef(t, manifestKeys[key], "backend flag %q is missing from the frontend manifest — add it so the Configure UI exposes it", key)
+ }
+ for key := range manifestKeys {
+ require.Truef(t, knownKeys[key], "frontend manifest flag %q is not in the backend allowlist (knownKeys) — the backend would reject it", key)
+ }
+
+ // 2. Defaults the backend actually applies must match what the UI shows.
+ // Derived from defaultConfig so a backend default change is caught here.
+ // Flags whose default is gh-ost's own zero value (e.g. max-load, the *-rbr
+ // toggles) are not held in defaultConfig and are left unchecked.
+ backendDefaults := map[string]string{
+ "attempt-instant-ddl": strconv.FormatBool(defaultConfig.attemptInstantDDL),
+ "allow-on-master": strconv.FormatBool(defaultConfig.allowedRunningOnMaster),
+ "heartbeat-interval-millis": strconv.FormatInt(defaultConfig.heartbeatIntervalMilliseconds, 10),
+ "nice-ratio": strconv.FormatFloat(defaultConfig.niceRatio, 'g', -1, 64),
+ "chunk-size": strconv.FormatInt(defaultConfig.chunkSize, 10),
+ "dml-batch-size": strconv.FormatInt(defaultConfig.dmlBatchSize, 10),
+ "max-lag-millis": strconv.FormatInt(defaultConfig.maxLagMillisecondsThrottleThreshold, 10),
+ "default-retries": strconv.FormatInt(defaultConfig.defaultNumRetries, 10),
+ "cut-over-lock-timeout-seconds": strconv.FormatInt(defaultConfig.cutoverLockTimeoutSeconds, 10),
+ "exponential-backoff-max-interval": strconv.FormatInt(defaultConfig.exponentialBackoffMaxInterval, 10),
+ }
+ for _, f := range manifest {
+ want, ok := backendDefaults[f.Key]
+ if !ok {
+ continue
+ }
+ require.Equalf(t, want, f.Default, "default for flag %q drifted from backend defaultConfig", f.Key)
+ }
+}
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index fac939d7de..3541ea146a 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1465,7 +1465,10 @@
"save-changes-before-continuing": "Please save or cancel your changes before continuing"
},
"ghost": {
- "requirements-not-met": "Ghost requirements not met: {{databases}}"
+ "configure": "Configure",
+ "parameters": "gh-ost parameters",
+ "requirements-not-met": "Ghost requirements not met: {{databases}}",
+ "reset-to-defaults": "Reset to defaults"
},
"go-to-plan-page": "Go to plan page",
"isolation-level": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index b5e4b8d44e..ba427fbb4f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1465,7 +1465,10 @@
"save-changes-before-continuing": "Guarde o cancele sus cambios antes de continuar."
},
"ghost": {
- "requirements-not-met": "Los requisitos de Ghost no se cumplen para: {{databases}}"
+ "configure": "Configurar",
+ "parameters": "Parámetros de gh-ost",
+ "requirements-not-met": "Los requisitos de Ghost no se cumplen para: {{databases}}",
+ "reset-to-defaults": "Restablecer valores predeterminados"
},
"go-to-plan-page": "Ir a la página del plan",
"isolation-level": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a40431afe6..0a6089907e 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1465,7 +1465,10 @@
"save-changes-before-continuing": "続行する前に変更を保存またはキャンセルしてください"
},
"ghost": {
- "requirements-not-met": "次のデータベースは Ghost の要件を満たしていません: {{databases}}"
+ "configure": "設定",
+ "parameters": "gh-ost パラメータ",
+ "requirements-not-met": "次のデータベースは Ghost の要件を満たしていません: {{databases}}",
+ "reset-to-defaults": "デフォルトに戻す"
},
"go-to-plan-page": "プランページへ移動",
"isolation-level": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 77fe07b513..68c8e46aec 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1465,7 +1465,10 @@
"save-changes-before-continuing": "Vui lòng lưu hoặc hủy thay đổi của bạn trước khi tiếp tục"
},
"ghost": {
- "requirements-not-met": "Các cơ sở dữ liệu sau không đáp ứng yêu cầu Ghost: {{databases}}"
+ "configure": "Cấu hình",
+ "parameters": "Tham số gh-ost",
+ "requirements-not-met": "Các cơ sở dữ liệu sau không đáp ứng yêu cầu Ghost: {{databases}}",
+ "reset-to-defaults": "Đặt lại về mặc định"
},
"go-to-plan-page": "Đi tới trang kế hoạch",
"isolation-level": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 374a3ce0f2..d0aaaadfd0 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1465,7 +1465,10 @@
"save-changes-before-continuing": "请保存或取消更改,然后再继续"
},
"ghost": {
- "requirements-not-met": "以下数据库不满足 Ghost 要求:{{databases}}"
+ "configure": "配置",
+ "parameters": "gh-ost 参数",
+ "requirements-not-met": "以下数据库不满足 Ghost 要求:{{databases}}",
+ "reset-to-defaults": "重置为默认值"
},
"go-to-plan-page": "前往计划页面",
"isolation-level": {
diff --git a/frontend/src/react/components/ghost/GhostFlagsButton.test.tsx b/frontend/src/react/components/ghost/GhostFlagsButton.test.tsx
new file mode 100644
index 0000000000..b30d25a074
--- /dev/null
+++ b/frontend/src/react/components/ghost/GhostFlagsButton.test.tsx
@@ -0,0 +1,161 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { describe, expect, test, vi } from "vitest";
+import { GHOST_PARAMETERS, withFlag } from "./constants";
+import { GhostFlagsButton } from "./GhostFlagsButton";
+import { GhostFlagsForm } from "./GhostFlagsForm";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+// Render the sheet content inline when open — jsdom has no portal/positioning,
+// and the save/cancel batching is what we want to assert.
+vi.mock("@/react/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>
+ open ? <div>{children}</div> : null,
+ SheetContent: ({ children }: { children: ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SheetHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ SheetTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
+ SheetBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ SheetFooter: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+const paramFor = (key: string) => {
+ const param = GHOST_PARAMETERS.find((p) => p.key === key);
+ if (!param) throw new Error(`unknown test param: ${key}`);
+ return param;
+};
+
+const toggleFlag = (root: ParentNode, flag: string) => {
+ const toggle = root
+ .querySelector(`[data-flag="${flag}"]`)
+ ?.querySelector('[role="switch"]');
+ if (!toggle) throw new Error(`no switch for ${flag}`);
+ fireEvent.click(toggle);
+};
+
+const clickButton = (name: RegExp | string) =>
+ fireEvent.click(screen.getByRole("button", { name }));
+
+describe("withFlag", () => {
+ test("sets a non-default override", () => {
+ expect(withFlag({}, paramFor("chunk-size"), "500")).toEqual({
+ "chunk-size": "500",
+ });
+ });
+
+ test("removes a key when set back to its default", () => {
+ expect(
+ withFlag({ "chunk-size": "500" }, paramFor("chunk-size"), "1000")
+ ).toEqual({});
+ });
+
+ test("writes booleans flipped away from their default", () => {
+ expect(withFlag({}, paramFor("allow-on-master"), false)).toEqual({
+ "allow-on-master": "false",
+ });
+ });
+
+ test("removes a boolean restored to its default", () => {
+ expect(
+ withFlag(
+ { "allow-on-master": "false" },
+ paramFor("allow-on-master"),
+ true
+ )
+ ).toEqual({});
+ });
+
+ test("clearing a string value removes the key", () => {
+ expect(
+ withFlag({ "max-load": "Threads_running=25" }, paramFor("max-load"), "")
+ ).toEqual({});
+ });
+
+ test("preserves other flags", () => {
+ expect(
+ withFlag({ "max-load": "x" }, paramFor("chunk-size"), "500")
+ ).toEqual({ "max-load": "x", "chunk-size": "500" });
+ });
+});
+
+describe("GhostFlagsForm", () => {
+ test("renders a control for every supported flag", () => {
+ const { container } = render(
+ <GhostFlagsForm value={{}} onChange={vi.fn()} />
+ );
+ expect(container.querySelectorAll("[data-flag]")).toHaveLength(
+ GHOST_PARAMETERS.length
+ );
+ });
+
+ test("toggling a boolean flag emits only that override", () => {
+ const onChange = vi.fn();
+ const { container } = render(
+ <GhostFlagsForm value={{}} onChange={onChange} />
+ );
+ toggleFlag(container, "allow-on-master");
+ expect(onChange).toHaveBeenCalledWith({ "allow-on-master": "false" });
+ });
+});
+
+describe("GhostFlagsButton", () => {
+ const TRIGGER = /plan\.ghost\.configure/;
+
+ test("disables the trigger when disabled", () => {
+ render(<GhostFlagsButton value={{}} onChange={vi.fn()} disabled />);
+ expect(screen.getByRole("button", { name: TRIGGER })).toBeDisabled();
+ });
+
+ test("shows the persisted override count", () => {
+ render(
+ <GhostFlagsButton value={{ "chunk-size": "500" }} onChange={vi.fn()} />
+ );
+ expect(screen.getByText("1")).toBeInTheDocument();
+ });
+
+ test("buffers edits and persists once on save", () => {
+ const onChange = vi.fn();
+ const { container } = render(
+ <GhostFlagsButton value={{}} onChange={onChange} />
+ );
+ clickButton(TRIGGER);
+ toggleFlag(container, "allow-on-master");
+ // No persist until the user saves.
+ expect(onChange).not.toHaveBeenCalled();
+ clickButton("common.save");
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith({ "allow-on-master": "false" });
+ });
+
+ test("cancel discards edits without persisting", () => {
+ const onChange = vi.fn();
+ const { container } = render(
+ <GhostFlagsButton value={{}} onChange={onChange} />
+ );
+ clickButton(TRIGGER);
+ toggleFlag(container, "allow-on-master");
+ clickButton("common.cancel");
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ test("save is disabled until the draft changes", () => {
+ render(<GhostFlagsButton value={{}} onChange={vi.fn()} />);
+ clickButton(TRIGGER);
+ expect(screen.getByRole("button", { name: "common.save" })).toBeDisabled();
+ });
+
+ test("reset clears the draft, then save persists an empty map", () => {
+ const onChange = vi.fn();
+ render(
+ <GhostFlagsButton value={{ "chunk-size": "500" }} onChange={onChange} />
+ );
+ clickButton(TRIGGER);
+ clickButton("plan.ghost.reset-to-defaults");
+ clickButton("common.save");
+ expect(onChange).toHaveBeenCalledWith({});
+ });
+});
diff --git a/frontend/src/react/components/ghost/GhostFlagsButton.tsx b/frontend/src/react/components/ghost/GhostFlagsButton.tsx
new file mode 100644
index 0000000000..dbb6ba49cb
--- /dev/null
+++ b/frontend/src/react/components/ghost/GhostFlagsButton.tsx
@@ -0,0 +1,105 @@
+import { isEqual } from "lodash-es";
+import { SlidersHorizontal } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Badge } from "@/react/components/ui/badge";
+import { Button } from "@/react/components/ui/button";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { GhostFlagsForm } from "./GhostFlagsForm";
+
+interface GhostFlagsButtonProps {
+ /** Current gh-ost flags parsed from the directive; `{}` = enabled, all defaults. */
+ value: Record<string, string>;
+ onChange: (next: Record<string, string>) => void;
+ disabled?: boolean;
+}
+
+/**
+ * "Configure" entry point for online-migration (gh-ost) parameters. Opens a Sheet
+ * that edits the flags carried by the `-- gh-ost = {...}` directive; only
+ * non-default values are written, matching the backend
+ * (`backend/component/ghost/config.go`).
+ *
+ * Edits are buffered in a local draft and the directive is written (via
+ * `onChange`) only when the user clicks Save — persisting on every keystroke would
+ * refetch and re-render the whole plan, flickering the page. Cancel/Escape/scrim
+ * discard the draft.
+ */
+export function GhostFlagsButton({
+ value,
+ onChange,
+ disabled,
+}: GhostFlagsButtonProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState(value);
+ const overrides = Object.keys(value).length;
+
+ const openSheet = () => {
+ // Seed the draft from the latest persisted value each time we open.
+ setDraft(value);
+ setOpen(true);
+ };
+ const save = () => {
+ onChange(draft);
+ setOpen(false);
+ };
+
+ return (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={openSheet}
+ >
+ <SlidersHorizontal className="size-3.5" />
+ {t("plan.ghost.configure")}
+ {overrides > 0 && (
+ <Badge variant="secondary" className="px-1.5 py-0 text-xs">
+ {overrides}
+ </Badge>
+ )}
+ </Button>
+ <Sheet open={open} onOpenChange={setOpen}>
+ <SheetContent width="panel">
+ <SheetHeader>
+ <SheetTitle>{t("plan.ghost.parameters")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody>
+ <GhostFlagsForm value={draft} onChange={setDraft} />
+ </SheetBody>
+ <SheetFooter className="justify-between">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={Object.keys(draft).length === 0}
+ onClick={() => setDraft({})}
+ >
+ {t("plan.ghost.reset-to-defaults")}
+ </Button>
+ <div className="flex gap-x-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setOpen(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button size="sm" disabled={isEqual(draft, value)} onClick={save}>
+ {t("common.save")}
+ </Button>
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+}
diff --git a/frontend/src/react/components/ghost/GhostFlagsForm.tsx b/frontend/src/react/components/ghost/GhostFlagsForm.tsx
new file mode 100644
index 0000000000..40a66c2def
--- /dev/null
+++ b/frontend/src/react/components/ghost/GhostFlagsForm.tsx
@@ -0,0 +1,88 @@
+import { Input } from "@/react/components/ui/input";
+import { NumberInput } from "@/react/components/ui/number-input";
+import { Switch } from "@/react/components/ui/switch";
+import { GHOST_PARAMETERS, type GhostParameter, withFlag } from "./constants";
+
+interface GhostFlagsFormProps {
+ /** Current gh-ost flags; only non-default overrides are present. */
+ value: Record<string, string>;
+ onChange: (next: Record<string, string>) => void;
+}
+
+/**
+ * The gh-ost parameter controls — one typed control per supported flag. Each
+ * control shows the backend default and `onChange` fires with the minimized flag
+ * map (only non-default overrides); the parent decides when to persist it.
+ */
+export function GhostFlagsForm({ value, onChange }: GhostFlagsFormProps) {
+ return (
+ <div className="flex flex-col gap-y-3">
+ {GHOST_PARAMETERS.map((param) => (
+ <GhostFlagRow
+ key={param.key}
+ param={param}
+ value={value}
+ onChange={onChange}
+ />
+ ))}
+ </div>
+ );
+}
+
+function GhostFlagRow({
+ param,
+ value,
+ onChange,
+}: {
+ param: GhostParameter;
+ value: Record<string, string>;
+ onChange: (next: Record<string, string>) => void;
+}) {
+ const current = value[param.key];
+ const set = (raw: string | number | boolean | null | undefined) =>
+ onChange(withFlag(value, param, raw));
+
+ return (
+ <div
+ data-flag={param.key}
+ className="flex min-h-7 items-center justify-between gap-x-4"
+ >
+ <span
+ className="truncate font-mono text-sm text-control"
+ title={param.key}
+ >
+ {param.key}
+ </span>
+ {param.type === "bool" ? (
+ <Switch
+ size="sm"
+ checked={
+ current !== undefined
+ ? current === "true"
+ : param.default === "true"
+ }
+ onCheckedChange={(checked) => set(checked)}
+ />
+ ) : param.type === "string" ? (
+ <Input
+ size="sm"
+ className="w-48"
+ aria-label={param.key}
+ placeholder={param.default || param.key}
+ value={current ?? ""}
+ onChange={(e) => set(e.target.value)}
+ />
+ ) : (
+ <NumberInput
+ size="sm"
+ className="w-48"
+ aria-label={param.key}
+ placeholder={param.default}
+ value={current !== undefined ? Number(current) : null}
+ step={param.type === "float" ? 0.1 : 1}
+ onValueChange={(v) => set(v)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/ghost/constants.ts b/frontend/src/react/components/ghost/constants.ts
new file mode 100644
index 0000000000..4cb8666398
--- /dev/null
+++ b/frontend/src/react/components/ghost/constants.ts
@@ -0,0 +1,67 @@
+/**
+ * Supported gh-ost parameters for online schema migration.
+ *
+ * The parameter list lives in `flags.json` — the single source of truth the
+ * Configure UI builds from. `TestFrontendFlagManifestInSync` in
+ * `backend/component/ghost/manifest_test.go` fails CI if `flags.json` drifts from
+ * the backend allowlist and defaults in `backend/component/ghost/config.go`
+ * (`knownKeys` + `defaultConfig`), so a flag added, removed, or re-defaulted on
+ * one side cannot silently diverge from the other.
+ *
+ * Configuration travels with the SQL statement as a single-line directive
+ * (`-- gh-ost = {...}`); only values that differ from the backend default are
+ * written, so the directive stays minimal.
+ */
+
+import flagManifest from "./flags.json";
+
+export type GhostParameterType = "bool" | "int" | "float" | "string";
+
+export interface GhostParameter {
+ key: string;
+ type: GhostParameterType;
+ /**
+ * The effective backend default, expressed as the string the directive would
+ * carry. An empty string means "no default / unset" (e.g. `max-load`).
+ */
+ default: string;
+}
+
+// Built from flags.json — ordered most-commonly-tuned first, booleans last.
+export const GHOST_PARAMETERS: GhostParameter[] = flagManifest.map(
+ (flag): GhostParameter => ({
+ key: flag.key,
+ type: flag.type as GhostParameterType,
+ default: flag.default,
+ })
+);
+
+/**
+ * Applies a single flag edit, keeping only overrides — values that differ from
+ * the backend default. The raw control value is coerced to the directive's
+ * string form (and dropped when it equals the default or is empty), mirroring
+ * the backend, which only overrides a default when the key is present. Unknown
+ * keys already in `flags` (e.g. hand-typed) are preserved.
+ */
+export function withFlag(
+ flags: Record<string, string>,
+ param: GhostParameter,
+ raw: string | number | boolean | null | undefined
+): Record<string, string> {
+ const next = { ...flags };
+ let value: string | undefined;
+ if (raw === undefined || raw === null) {
+ value = undefined;
+ } else if (param.type === "bool") {
+ value = raw ? "true" : "false";
+ } else {
+ const trimmed = String(raw).trim();
+ value = trimmed === "" ? undefined : trimmed;
+ }
+ if (value === undefined || value === param.default) {
+ delete next[param.key];
+ } else {
+ next[param.key] = value;
+ }
+ return next;
+}
diff --git a/frontend/src/react/components/ghost/flags.json b/frontend/src/react/components/ghost/flags.json
new file mode 100644
index 0000000000..3100f140d0
--- /dev/null
+++ b/frontend/src/react/components/ghost/flags.json
@@ -0,0 +1,17 @@
+[
+ { "key": "max-load", "type": "string", "default": "" },
+ { "key": "chunk-size", "type": "int", "default": "1000" },
+ { "key": "max-lag-millis", "type": "int", "default": "1500" },
+ { "key": "dml-batch-size", "type": "int", "default": "10" },
+ { "key": "nice-ratio", "type": "float", "default": "0" },
+ { "key": "cut-over-lock-timeout-seconds", "type": "int", "default": "10" },
+ { "key": "default-retries", "type": "int", "default": "60" },
+ { "key": "exponential-backoff-max-interval", "type": "int", "default": "64" },
+ { "key": "heartbeat-interval-millis", "type": "int", "default": "100" },
+ { "key": "throttle-control-replicas", "type": "string", "default": "" },
+ { "key": "allow-on-master", "type": "bool", "default": "true" },
+ { "key": "attempt-instant-ddl", "type": "bool", "default": "true" },
+ { "key": "switch-to-rbr", "type": "bool", "default": "false" },
+ { "key": "assume-rbr", "type": "bool", "default": "false" },
+ { "key": "assume-master-host", "type": "bool", "default": "false" }
+]
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 f2f67d1b02..a7f20944ba 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -18,6 +18,7 @@ import {
} from "@/connect";
import { EngineIcon } from "@/react/components/EngineIcon";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { GhostFlagsButton } from "@/react/components/ghost/GhostFlagsButton";
import { RouterLink } from "@/react/components/RouterLink";
import { Alert } from "@/react/components/ui/alert";
import {
@@ -1202,6 +1203,15 @@ function OptionsSection({
/>
</div>
</Tooltip>
+ {ghostEnabled && (
+ <GhostFlagsButton
+ value={currentGhostConfig ?? {}}
+ disabled={!allowChange || isSheetOversize}
+ onChange={(next) =>
+ void persistStatement(updateGhostConfig(sheetStatement, next))
+ }
+ />
+ )}
</div>
</div>
) : (
diff --git a/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.test.ts b/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.test.ts
new file mode 100644
index 0000000000..d64ba857ef
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from "vitest";
+import {
+ getGhostConfig,
+ isGhostEnabled,
+ updateGhostConfig,
+} from "./directiveUtils";
+
+// The backend matches the `-- gh-ost = {...}` directive with a multiline search
+// (backend/component/ghost/directive.go), so a directive below the SQL is valid.
+// These tests lock the frontend to the same "anywhere" semantics so the Configure
+// editor reads and rewrites such directives instead of dropping their flags.
+describe("getGhostConfig — directive position", () => {
+ test("reads a leading directive", () => {
+ const statement = `-- gh-ost = {"chunk-size":"500"}\nALTER TABLE t ADD COLUMN c INT;`;
+ expect(getGhostConfig(statement)).toEqual({ "chunk-size": "500" });
+ });
+
+ test("reads a directive that follows the SQL", () => {
+ const statement = `ALTER TABLE t ADD COLUMN c INT;\n-- gh-ost = {"max-load":"Threads_running=50"}`;
+ expect(getGhostConfig(statement)).toEqual({
+ "max-load": "Threads_running=50",
+ });
+ });
+
+ test("detects a non-leading directive as enabled", () => {
+ expect(isGhostEnabled("ALTER TABLE t;\n-- gh-ost = {}")).toBe(true);
+ });
+});
+
+describe("updateGhostConfig — non-leading directive", () => {
+ test("rewrites a single leading directive without dropping existing flags", () => {
+ const statement = `ALTER TABLE t ADD COLUMN c INT;\n-- gh-ost = {"max-load":"Threads_running=50"}`;
+ const updated = updateGhostConfig(statement, {
+ "max-load": "Threads_running=50",
+ "chunk-size": "500",
+ });
+
+ // Exactly one directive — the below-the-SQL one is not left as a duplicate.
+ expect(updated.match(/--\s*gh-ost\s*=/g)).toHaveLength(1);
+ // It carries both the pre-existing and the newly-edited flag.
+ expect(getGhostConfig(updated)).toEqual({
+ "max-load": "Threads_running=50",
+ "chunk-size": "500",
+ });
+ expect(updated).toContain("ALTER TABLE t ADD COLUMN c INT;");
+ });
+
+ test("removing the directive strips it wherever it sits", () => {
+ const statement = `ALTER TABLE t ADD COLUMN c INT;\n-- gh-ost = {"max-load":"x"}`;
+ const updated = updateGhostConfig(statement, undefined);
+
+ expect(isGhostEnabled(updated)).toBe(false);
+ expect(updated).not.toMatch(/--\s*gh-ost/);
+ expect(updated).toContain("ALTER TABLE t ADD COLUMN c INT;");
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts b/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts
index 5c72da7ce7..b4c1816137 100644
--- a/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts
+++ b/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts
@@ -102,6 +102,30 @@ export function parseStatement(statement: string): ParsedStatement {
}
}
+ // Unlike the positional txn-mode/isolation directives, the gh-ost directive may
+ // appear anywhere in the statement, not only the leading comment block scanned
+ // above. The backend (backend/component/ghost/directive.go) matches it with a
+ // multiline search, reads the first occurrence, and strips them all. Mirror
+ // that here so editing rewrites a single leading directive instead of silently
+ // dropping a below-the-SQL directive's flags (or leaving a stale duplicate).
+ for (let i = 0; i < lines.length; i++) {
+ if (directiveLines.has(i)) {
+ continue;
+ }
+ const ghostMatch = lines[i].match(GHOST_DIRECTIVE_REGEX);
+ if (!ghostMatch) {
+ continue;
+ }
+ directiveLines.add(i);
+ if (result.ghostConfig === undefined) {
+ try {
+ result.ghostConfig = JSON.parse(ghostMatch[1]);
+ } catch {
+ // Invalid JSON; the line is still stripped, keep looking for a valid one.
+ }
+ }
+ }
+
// Build remaining content without directive lines
const remainingLines = lines.filter((_, i) => !directiveLines.has(i));
const remainingContent = remainingLines.join("\n");