:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): stop the variables bar losing a row while you add one (#90180)
Sinan Kucukkoseler2eb3c5b3d882
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 9656c5d92377..39795a19c311 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -88,7 +88,7 @@ import type {} from '../Nodes/notebookNodeContent'import type { notebookNodeLogicType } from '../Nodes/notebookNodeLogic'import { NotebookNodeType, NotebookSyncStatus, NotebookTarget, NotebookType } from '../types'-import type { NotebookListItemType } from '../types'+import type { NotebookListItemType, NotebookVariableApi } from '../types'import { updateContentHeading } from '../utils'import { NotebookArtifactApplyMode } from './markdownNotebookRuntime'import {@@ -125,8 +125,12 @@ import {NotebookVariable,getNotebookVariableConflictNames,getNotebookVariableErrors,+ droppedSavedNotebookVariables,getRunnableNotebookVariables,+ getSavableNotebookVariables,+ isNotebookVariableDraft,parseNotebookVariables,+ sameNotebookVariables,} from './notebookVariables'/** Save debounce for local-only notebooks (scratchpad, canvas), which don't sync to the server. */@@ -316,6 +320,7 @@ export interface notebookLogicValues {frameNodeSummaries: NotebookFrameNodeSummary[]getSharedCachedInlineQueryResults: (nodeId: string | null | undefined) => AnyResponseType | nullgetSharedCachedInsight: (shortId: string | null | undefined) => InsightModel | null+ hasUnsavedVariables: booleanhogqlSqlNodeIndices: Map<string, number>hogqlSqlNodeSummaries: HogqlSqlNodeSummary[]isEditable: boolean@@ -487,6 +492,9 @@ export interface notebookLogicActions {value: true}}+ notebookVariablesSaved: (variables: NotebookVariableApi[]) => {+ variables: NotebookVariableApi[]+ }openShareModal: () => {value: true}@@ -651,13 +659,14 @@ export interface notebookLogicMeta {markdownEditorNodeId: (content: JSONContent) => stringmarkdownEditorValue: (markdownEditorDraft: string | null, markdownEditorMarkdown: string) => stringtitle: (notebook: NotebookType | null, content: JSONContent) => string+ hasUnsavedVariables: (localVariables: NotebookVariable[] | null, notebook: NotebookType | null) => booleansyncStatus: (notebook: NotebookType | null,notebookLoading: boolean,localContent: JSONContent | null,isLocalOnly: boolean,previewContent: JSONContent | null,- localVariables: NotebookVariable[] | null+ hasUnsavedVariables: boolean) => NotebookSyncStatuseditingNodeLogics: (editingNodeIds: Record<string, true>,@@ -772,6 +781,7 @@ export const notebookLogic = kea<notebookLogicType>([clearLocalContent: true,setVariables: (variables: NotebookVariable[]) => ({ variables }),clearLocalVariables: true,+ notebookVariablesSaved: (variables: NotebookVariableApi[]) => ({ variables }),setPreviewContent: (jsonContent: JSONContent) => ({ jsonContent }),clearPreviewContent: true,loadNotebook: true,@@ -1207,6 +1217,10 @@ export const notebookLogic = kea<notebookLogicType>([saveNotebookSuccess: (state, { notebook }) => keepNewestNotebookResponse(state, notebook),applyRemoteNotebookContent: (state, { content, version }) =>state && version > state.version ? { ...state, content, version } : state,+ // A variables-only PATCH leaves `version` alone server-side, so only this field is+ // newer. Merging it lets the local copy be dropped without the bar snapping back to+ // the list the notebook was loaded with.+ notebookVariablesSaved: (state, { variables }) => (state ? { ...state, variables } : state),},}),selectors({@@ -1310,15 +1324,36 @@ export const notebookLogic = kea<notebookLogicType>([return getMarkdownNotebookTitle(content) || notebook?.title || 'Untitled'},],+ /**+ * Whether the bar holds an edit the server does not have yet. Compared on the savable+ * declarations only, so a draft row the person has not named cannot leave the notebook+ * reporting unsaved work forever.+ */+ hasUnsavedVariables: [+ (s) => [s.localVariables, s.notebook],+ (localVariables: NotebookVariable[] | null, notebook: NotebookType | null): boolean =>+ localVariables !== null &&+ !sameNotebookVariables(+ getSavableNotebookVariables(localVariables),+ parseNotebookVariables(notebook?.variables)+ ),+ ],syncStatus: [- (s) => [s.notebook, s.notebookLoading, s.localContent, s.isLocalOnly, s.previewContent, s.localVariables],+ (s) => [+ s.notebook,+ s.notebookLoading,+ s.localContent,+ s.isLocalOnly,+ s.previewContent,+ s.hasUnsavedVariables,+ ],(notebook: NotebookType | null,notebookLoading: boolean,localContent: JSONContent | null,isLocalOnly: boolean,previewContent: JSONContent | null,- localVariables: NotebookVariable[] | null+ hasUnsavedVariables: boolean): NotebookSyncStatus => {if (previewContent || notebook?.is_template) {return 'synced'@@ -1329,7 +1364,7 @@ export const notebookLogic = kea<notebookLogicType>([}// Variables save on their own PATCH, so an edit to them is unsaved work even// when the document itself is clean.- if (!notebook || (!localContent && !localVariables)) {+ if (!notebook || (!localContent && !hasUnsavedVariables)) {return 'synced'}@@ -1436,8 +1471,12 @@ export const notebookLogic = kea<notebookLogicType>([],variableErrors: [(s) => [s.variables, s.content],- (variables: NotebookVariable[], content: JSONContent): (string | null)[] =>- getNotebookVariableErrors(variables, getNotebookVariableConflictNames(content)),+ (variables: NotebookVariable[], content: JSONContent): (string | null)[] => {+ const errors = getNotebookVariableErrors(variables, getNotebookVariableConflictNames(content))+ // A row that was just added has no name yet. Reporting that back before the+ // person can type is noise, not feedback.+ return errors.map((error, index) => (isNotebookVariableDraft(variables[index]) ? null : error))+ },],// Only valid, unique declarations are safe to bind into a run.runnableVariables: [@@ -1562,19 +1601,56 @@ export const notebookLogic = kea<notebookLogicType>([return}await breakpoint(500)++ // Adding a row, or typing a name the API would reject, changes nothing the server can+ // store. Saving anyway returned a 400 and an error toast for a row the person had not+ // finished filling in.+ if (!values.hasUnsavedVariables) {+ return+ }++ // Send only what the API accepts. One unnamed row would fail the whole PATCH and take+ // the valid declarations with it.+ const savable = getSavableNotebookVariables(values.variables)+ const saved = parseNotebookVariables(values.notebook?.variables)+ const heldBack = savable.length !== values.variables.length++ // A row that is still on screen but too invalid to send is withheld from the payload,+ // and a PATCH replaces the whole list. Sending it would delete the saved variable+ // behind that row, so a typo in a name would drop the value it holds. Hold the whole+ // save instead: the bar keeps the edit and goes on reporting unsaved work. A row the+ // person actually removed leaves nothing behind, so a real deletion still saves.+ if (heldBack && droppedSavedNotebookVariables(savable, saved).length > 0) {+ return+ }++ let response: NotebookTypetry {- const response = await api.notebooks.update(props.shortId, { variables: values.variables })- actions.receiveNotebookUpdate(response)- // Only drop the local copy when it still matches what we just saved — a keystroke- // that landed during the request is newer and must survive to its own save.- if (values.localVariables === variables) {- actions.clearLocalVariables()- }+ response = await api.notebooks.update(props.shortId, { variables: savable })} catch (error) {// The bar keeps the edit, so the next change retries it. Losing a value silently// would be worse than an error the user can act on.lemonToast.error('Could not save notebook variables')posthog.captureException(error)+ return+ }++ // The debounce holds the next request but does not cancel one already in flight, so+ // two saves can overlap. Applying this older response would revert the bar to the list+ // the newer save replaced. Outside the catch above: this throws to abort, not to fail.+ breakpoint()++ actions.receiveNotebookUpdate(response)+ // notebooksModel only holds list rows, so the notebook this logic renders from needs+ // the saved list too. Without it the bar drops back to the copy the page loaded with+ // and the row the person just named disappears. An absent field falls back to what we+ // sent, which the server accepted, rather than to "no variables".+ actions.notebookVariablesSaved(response.variables ?? savable)+ // Only drop the local copy when it still matches what we just saved — a keystroke that+ // landed during the request is newer and must survive to its own save. A draft that+ // was held back lives only in the local copy, so that copy has to stay.+ if (values.localVariables === variables && !heldBack) {+ actions.clearLocalVariables()}},connectMarkdownUpdateStream: () => {diff --git a/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.tsindex 5c67b00058ae..5e0955fcdb1f 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookVariables.test.ts@@ -7,6 +7,7 @@ import {getNotebookVariableConflictNames,getNotebookVariableErrors,getRunnableNotebookVariables,+ getSavableNotebookVariables,parseNotebookVariables,} from './notebookVariables'@@ -106,6 +107,26 @@ describe('notebookVariables', () => {})})+ describe('getSavableNotebookVariables', () => {+ it('drops a declaration the API would reject', () => {+ // One bad name fails the whole PATCH, so it must not travel with the good ones.+ expect(+ getSavableNotebookVariables([+ country,+ { name: '', type: 'string', value: '' },+ { name: 'look-back', type: 'number', value: 7 },+ ])+ ).toEqual([country])+ })++ it("keeps a declaration that clashes with a cell's output dataframe", () => {+ // The API stores this happily. Filtering it here would delete the person's variable+ // because some other cell was renamed to the same word.+ const clashing: NotebookVariable = { name: 'sql_df', type: 'string', value: 'US' }+ expect(getSavableNotebookVariables([clashing])).toEqual([clashing])+ })+ })+describe('getRunnableNotebookVariables', () => {it('sends only the declarations that pass validation', () => {// An invalid name would reach the backend as a variable no cell can read, and adiff --git a/frontend/src/scenes/notebooks/Notebook/notebookVariables.ts b/frontend/src/scenes/notebooks/Notebook/notebookVariables.tsindex 13bac2f9d979..443a590d2ec4 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookVariables.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookVariables.ts@@ -175,6 +175,47 @@ export function getRunnableNotebookVariables(return variables.filter((_, index) => errors[index] === null)}+/**+ * A row the person added but has not named yet. It cannot be referenced or saved, so the bar+ * treats it as a draft: no validation message, and no attempt to persist it.+ */+export function isNotebookVariableDraft(variable: NotebookVariable): boolean {+ return !variable.name+}++/**+ * The declarations the API accepts. Conflicts with a cell's dataframe name are deliberately not+ * filtered here: the server stores such a declaration happily, and dropping it would delete the+ * person's work because another cell was renamed. One bad row must not fail the whole PATCH.+ */+export function getSavableNotebookVariables(variables: NotebookVariable[]): NotebookVariable[] {+ const errors = getNotebookVariableErrors(variables)+ return variables.filter((_, index) => errors[index] === null)+}++/**+ * The saved declarations that `savable` would remove. A PATCH replaces the whole list, so this is+ * what the server would lose by sending it.+ */+export function droppedSavedNotebookVariables(+ savable: NotebookVariable[],+ saved: NotebookVariable[]+): NotebookVariable[] {+ const savableNames = new Set(savable.map((variable) => variable.name))+ return saved.filter((variable) => !savableNames.has(variable.name))+}++/** Whether two declaration lists hold the same variables in the same order. */+export function sameNotebookVariables(a: NotebookVariable[], b: NotebookVariable[]): boolean {+ return (+ a.length === b.length &&+ a.every(+ (variable, index) =>+ variable.name === b[index].name && variable.type === b[index].type && variable.value === b[index].value+ )+ )+}+/*** Whether a cell's code reads `variableName`. SQL reads it as a `{name}` placeholder; Python reads* it as a plain global, so the rough identifier scan is reused (a false positive only marks andiff --git a/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.tsindex 98f0fe65a5f3..668140bde6f3 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookVariablesWiring.test.ts@@ -44,6 +44,7 @@ const notebookFixture = {describe('notebook variables wiring', () => {let logic: ReturnType<typeof notebookLogic.build>let stalenessLogic: ReturnType<typeof notebookNodeStalenessLogic.build>+ let updateSpy: jest.SpyInstancebeforeEach(() => {localStorage.clear()@@ -56,7 +57,14 @@ describe('notebook variables wiring', () => {})initKeaTests()jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)- jest.spyOn(api.notebooks, 'update').mockResolvedValue({ ...notebookFixture, version: 2 })+ // Echoes the saved variables, as the API does. Returning the fixture unchanged would+ // hide a save that never reaches the bar.+ updateSpy = jest+ .spyOn(api.notebooks, 'update')+ .mockImplementation(async (_shortId: string, data: Record<string, any>) => ({+ ...notebookFixture,+ ...data,+ }))stalenessLogic = notebookNodeStalenessLogic({ shortId: SHORT_ID })stalenessLogic.mount()@@ -65,6 +73,18 @@ describe('notebook variables wiring', () => {logic.actions.loadNotebook()})+ // The save debounces by 500ms, so the request appears only after it elapses. Polled rather+ // than slept past, so a slow machine waits longer instead of failing.+ const waitForSaveRequests = async (count: number): Promise<void> => {+ for (let attempt = 0; attempt < 200; attempt++) {+ if (updateSpy.mock.calls.length >= count) {+ return+ }+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+ throw new Error(`Expected ${count} save requests, saw ${updateSpy.mock.calls.length}`)+ }+afterEach(() => {logic?.unmount()stalenessLogic?.unmount()@@ -86,6 +106,110 @@ describe('notebook variables wiring', () => {expect(logic.values.variables).toEqual([{ name: 'country', type: 'string', value: 'US' }])})+ it('keeps the saved value once the save lands', async () => {+ // The notebook this logic renders from is not the list row notebooksModel holds, so the+ // save has to be written back to it. Without that the bar drops the local copy and falls+ // back to the list the page loaded with, reverting the edit the person just made.+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setVariables([{ name: 'country', type: 'string', value: 'DE' }])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.variables).toEqual([{ name: 'country', type: 'string', value: 'DE' }])+ expect(logic.values.syncStatus).toEqual('synced')+ })++ it('adding an empty row neither saves nor reports an error', async () => {+ // Clicking "Add variable" used to PATCH a nameless row straight away: the API rejected it+ // and the person got an error toast for a row they had not started filling in.+ await expectLogic(logic).toFinishAllListeners()+ updateSpy.mockClear()++ logic.actions.setVariables([+ { name: 'country', type: 'string', value: 'US' },+ { name: '', type: 'string', value: '' },+ ])+ await expectLogic(logic).toFinishAllListeners()++ expect(updateSpy).not.toHaveBeenCalled()+ expect(logic.values.variableErrors).toEqual([null, null])+ expect(logic.values.syncStatus).toEqual('synced')+ })++ it('an unnamed row does not hold back an edit to a named one', async () => {+ // The draft is withheld from the PATCH rather than blocking it, and it stays in the bar+ // so the person can carry on naming it.+ await expectLogic(logic).toFinishAllListeners()+ updateSpy.mockClear()++ logic.actions.setVariables([+ { name: 'country', type: 'string', value: 'DE' },+ { name: '', type: 'string', value: '' },+ ])+ await expectLogic(logic).toFinishAllListeners()++ expect(updateSpy).toHaveBeenCalledWith(SHORT_ID, {+ variables: [{ name: 'country', type: 'string', value: 'DE' }],+ })+ expect(logic.values.variables).toEqual([+ { name: 'country', type: 'string', value: 'DE' },+ { name: '', type: 'string', value: '' },+ ])+ })++ it.each([+ ['an invalid name', '2days'],+ ['a cleared name', ''],+ ])('holds the save while a saved variable carries %s', async (_case, name) => {+ // The payload replaces the whole list, so sending it without the unsendable row would+ // delete `country` on the server. A typo must not drop the value the row holds.+ await expectLogic(logic).toFinishAllListeners()+ updateSpy.mockClear()++ logic.actions.setVariables([{ name, type: 'string', value: 'US' }])+ await expectLogic(logic).toFinishAllListeners()++ expect(updateSpy).not.toHaveBeenCalled()+ // Nothing reached the server, so the bar has to keep saying so.+ expect(logic.values.syncStatus).toEqual('unsaved')+ })++ it('removing a variable still saves the removal', async () => {+ // The guard above must not block a deletion: a removed row leaves nothing on screen.+ await expectLogic(logic).toFinishAllListeners()+ updateSpy.mockClear()++ logic.actions.setVariables([])+ await expectLogic(logic).toFinishAllListeners()++ expect(updateSpy).toHaveBeenCalledWith(SHORT_ID, { variables: [] })+ expect(logic.values.variables).toEqual([])+ })++ it('ignores a save response that lands after a newer one', async () => {+ // The debounce holds the next request but does not cancel one in flight, so two saves can+ // overlap. The slower, older response must not revert the bar to the list it replaced.+ await expectLogic(logic).toFinishAllListeners()+ updateSpy.mockClear()++ const pending: Array<() => void> = []+ updateSpy.mockImplementation(+ (_shortId: string, data: Record<string, any>) =>+ new Promise((resolve) => pending.push(() => resolve({ ...notebookFixture, ...data })))+ )++ logic.actions.setVariables([{ name: 'country', type: 'string', value: 'FIRST' }])+ await waitForSaveRequests(1)+ logic.actions.setVariables([{ name: 'country', type: 'string', value: 'SECOND' }])+ await waitForSaveRequests(2)++ // Newer first, then the straggler.+ pending[1]()+ pending[0]()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.variables).toEqual([{ name: 'country', type: 'string', value: 'SECOND' }])+ })+it('an edit counts as unsaved work until the save lands', async () => {// Variables save on their own PATCH, so the document being clean must not report// "synced" while a variable edit is still pending — that also drives the