: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
feat(notebooks): show what a kernel costs before you start it (#91023)
Sinan Kucukkoseler6d44a91bfb4b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 22eba92ebf90..7c18efa16740 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7820,6 +7820,18 @@ snapshots:hash: v1.k794b7964.434383db5739f05638540be4be2f7671cdb35cca73c32df11f324feb17f3685c.suVpXuPkYmQJtBx6L0JVf4p_bj929kIWSY2fds0lPfwscenes-app-notebooks-components-notebook-select-button--with-slow-network-response--light:hash: v1.k794b7964.678b0f73befa0690622fd5eb7a920f5c25919af7a9b516a08756e866b37de352.QhzKGfEQA_MQykTL8uuyOryngt75iNv9BydvL5ckPjQ+ scenes-app-notebooks-kernel-info--running-on-a-preset--dark:+ hash: v1.k794b7964.d62b25b6e0f4fff01b9df44f2f40e0b24cf7e6329dca8e9f6091ad9ea88f017d.wdVwj4YTiAv4gmWs6lmZTH6lWwlUqSbogrXazNvRfI8+ scenes-app-notebooks-kernel-info--running-on-a-preset--light:+ hash: v1.k794b7964.ebc33548c9baf8e642e685eae0264bb557ba88ceb8032bba24eb834005089bc2.SF6y4mNNp--Yrl7XCZXa2SyGyDxM_tkiOrQROWAlouk+ scenes-app-notebooks-kernel-info--stopped-on-docker--dark:+ hash: v1.k794b7964.d62b25b6e0f4fff01b9df44f2f40e0b24cf7e6329dca8e9f6091ad9ea88f017d.dvIvjZF5xvw5NpLVzfIks8i7MFnIDcvnG2Fpd92Y-Go+ scenes-app-notebooks-kernel-info--stopped-on-docker--light:+ hash: v1.k794b7964.ebc33548c9baf8e642e685eae0264bb557ba88ceb8032bba24eb834005089bc2.Fu-cPnrGmbGNohBcFtwNqF_ueQnGg0sMTFXSY0pwCc4+ scenes-app-notebooks-kernel-info--tuned-by-hand--dark:+ hash: v1.k794b7964.d62b25b6e0f4fff01b9df44f2f40e0b24cf7e6329dca8e9f6091ad9ea88f017d.rthWhOQfoKEqDMuIGx_ZOmvmroexiFo8wln3H6uwFFw+ scenes-app-notebooks-kernel-info--tuned-by-hand--light:+ hash: v1.k794b7964.ebc33548c9baf8e642e685eae0264bb557ba88ceb8032bba24eb834005089bc2.vMOgc8ABwVSTG1B4eojy8V3xDViIPDZj3BmBVCkvXycscenes-app-notebooks-nodes-customer-journey--all-steps-completed--dark:hash: v1.k794b7964.21a8db46b074c796548d4e0fc63caf6443807d16fc5bf18de4d8702336870cd8.F16rPJkkmnadbRylNt9D1y4vd-_qggONDZaX0ErA27gscenes-app-notebooks-nodes-customer-journey--all-steps-completed--light:diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsxindex e9fd101f78c3..67abc94a831c 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx@@ -40,7 +40,12 @@ function useNotebookDataframeTreeSections(): TreeDataItem[] {const nodeLogic = useMountedLogic(notebookNodeLogic)const { notebookLogic } = useValues(nodeLogic)const { frameNodeSummaries } = useValues(notebookLogic)- const { localFrames } = useValues(notebookKernelInfoLogic({ shortId: notebookLogic.props.shortId }))+ const { localFrames } = useValues(+ notebookKernelInfoLogic({+ shortId: notebookLogic.props.shortId,+ isShared: !!notebookLogic.props.cachedNotebook,+ })+ )return useMemo(() => buildDataframeTreeSection(frameNodeSummaries, localFrames), [frameNodeSummaries, localFrames])}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.stories.tsxnew file mode 100644index 000000000000..2bec5ba2d8b9--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.stories.tsx@@ -0,0 +1,135 @@+import { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'++import { mswDecorator } from '~/mocks/browser'++import { NotebookType } from '../types'+import notebook12345Json from './__mocks__/notebook-12345.json'+import { NotebookKernelInfo } from './NotebookKernelInfo'+import { notebookLogic } from './notebookLogic'++const SHORT_ID = '12345'++const COMPUTE_OPTIONS = {+ currency: 'USD',+ cpu_rate_per_core_hour: 0.2,+ memory_rate_per_gb_hour: 0.025,+ default_preset_key: 'small',+ presets: [+ {+ key: 'small',+ name: 'Small',+ description: 'Exploring data and working with small dataframes.',+ cpu_cores: 1,+ memory_gb: 2,+ hourly_price: 0.25,+ },+ {+ key: 'balanced',+ name: 'Balanced',+ description: 'Most analysis work.',+ cpu_cores: 4,+ memory_gb: 8,+ hourly_price: 1,+ },+ {+ key: 'large',+ name: 'Large',+ description: 'Large joins and cells that run for a while.',+ cpu_cores: 8,+ memory_gb: 16,+ hourly_price: 2,+ },+ {+ key: 'high_memory',+ name: 'High memory',+ description: 'Dataframes that run out of memory on the other presets.',+ cpu_cores: 8,+ memory_gb: 32,+ hourly_price: 2.4,+ },+ ],+ allowed_cpu_cores: [0.125, 0.25, 0.5, 1, 2, 4, 6, 8, 16, 32, 64],+ allowed_memory_gb: [0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256],+ allowed_idle_timeout_seconds: [600, 1800, 3600, 10800, 21600, 43200],+}++const kernelStatus = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({+ backend: 'modal',+ status: 'running',+ frames: [],+ cpu_cores: 1,+ memory_gb: 2,+ disk_size_gb: 10,+ idle_timeout_seconds: 3600,+ hourly_price: 0.25,+ preset_key: 'small',+ ...overrides,+})++const meta: Meta<typeof NotebookKernelInfo> = {+ title: 'Scenes-App/Notebooks/Kernel info',+ component: NotebookKernelInfo,+ // The widget lives in the notebook's right column, so pin the story to that column's width.+ // Its price column is the piece most at risk of wrapping when a preset name grows.+ decorators: [+ (Story) => (+ <BindLogic+ logic={notebookLogic}+ props={{ shortId: SHORT_ID, cachedNotebook: notebook12345Json as unknown as NotebookType }}+ >+ <div className="w-[20rem]">+ <Story />+ </div>+ </BindLogic>+ ),+ ],+ parameters: {+ layout: 'padded',+ testOptions: { snapshotTargetSelector: '.NotebookColumn__widget' },+ },+}+export default meta++type Story = StoryObj<typeof NotebookKernelInfo>++export const RunningOnAPreset: Story = {+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/notebooks/${SHORT_ID}/kernel/status`]: kernelStatus(),+ '/api/projects/:team_id/notebooks/kernel/compute_options': COMPUTE_OPTIONS,+ },+ }),+ ],+}++export const TunedByHand: Story = {+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/notebooks/${SHORT_ID}/kernel/status`]: kernelStatus({+ cpu_cores: 6,+ memory_gb: 32,+ hourly_price: 2,+ preset_key: null,+ }),+ '/api/projects/:team_id/notebooks/kernel/compute_options': COMPUTE_OPTIONS,+ },+ }),+ ],+}++export const StoppedOnDocker: Story = {+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/notebooks/${SHORT_ID}/kernel/status`]: kernelStatus({+ backend: 'docker',+ status: 'stopped',+ }),+ '/api/projects/:team_id/notebooks/kernel/compute_options': COMPUTE_OPTIONS,+ },+ }),+ ],+}diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.tsxindex 4460b419d5b8..454cd5a5fed6 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookKernelInfo.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { useState } from 'react'import { IconInfo } from '@posthog/icons'-import { LemonButton, LemonSelect, LemonTag, Popover } from '@posthog/lemon-ui'+import { LemonButton, LemonSelect, LemonTag, Popover, Tooltip } from '@posthog/lemon-ui'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'@@ -10,7 +10,7 @@ import { LemonWidget } from 'lib/lemon-ui/LemonWidget'import { Spinner } from 'lib/lemon-ui/Spinner'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'-import { cpuCoreOptions, idleTimeoutOptions, memoryGbOptions, notebookKernelInfoLogic } from './notebookKernelInfoLogic'+import { idleTimeoutOptions, notebookKernelInfoLogic } from './notebookKernelInfoLogic'import { notebookLogic } from './notebookLogic'import { notebookSettingsLogic } from './notebookSettingsLogic'@@ -26,15 +26,15 @@ const formatMemory = (value: number): string => {return `${value} GB`}-const CPU_PRICE_PER_CORE_HOUR = 0.1419-const MEMORY_PRICE_PER_GIB_HOUR = 0.0242-const formatHourlyPrice = (value: number): string => `$${value.toFixed(2)} / h`+const PRICE_TOOLTIP =+ 'Billed for as long as the sandbox runs, whether or not a cell is running. Stop it to stop the charge.'+export const NotebookKernelInfo = (): JSX.Element => {- const { shortId } = useValues(notebookLogic)+ const { shortId, isShared } = useValues(notebookLogic)const { setShowKernelInfo } = useActions(notebookSettingsLogic)- const logic = notebookKernelInfoLogic({ shortId })+ const logic = notebookKernelInfoLogic({ shortId, isShared })useAttachedLogic(logic, notebookLogic)const {kernelInfo,@@ -53,18 +53,27 @@ export const NotebookKernelInfo = (): JSX.Element => {code,cpuIndex,memoryIndex,+ cpuOptions,+ memoryOptions,+ computePresets,+ selectedPresetKey,+ selectedHourlyPrice,+ computeBlockedReason,+ computeOptionsFailed,} = useValues(logic)const {clearExecution,executeKernel,+ loadComputeOptions,loadKernelInfo,restartKernel,saveKernelConfig,startKernel,stopKernel,setCode,- setCpuIndex,- setMemoryIndex,+ setCpuCores,+ setMemoryGb,+ applyComputePreset,setIdleTimeoutSeconds,resetConfigToKernel,} = useActions(logic)@@ -83,7 +92,7 @@ export const NotebookKernelInfo = (): JSX.Element => {</div>) : nullconst startOrRestartKernel = (): void => {- if (isModalKernel && hasConfigChanges) {+ if (isModalKernel && hasConfigChanges && selectedCpu != null && selectedMemory != null) {saveKernelConfig({cpu_cores: selectedCpu,@@ -129,7 +138,10 @@ export const NotebookKernelInfo = (): JSX.Element => {<LemonButtonsize="xsmall"type="secondary"- onClick={() => loadKernelInfo()}+ onClick={() => {+ loadKernelInfo()+ loadComputeOptions()+ }}loading={actionInFlight.refresh}disabled={hasActionInFlight && !actionInFlight.refresh}>@@ -144,7 +156,7 @@ export const NotebookKernelInfo = (): JSX.Element => {</div>) : kernelInfo ? (<div className="space-y-3 p-3">- <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-center gap-2"><div className="flex flex-wrap items-center gap-2">{statusInfo ? <LemonTag type={statusInfo.tone}>{statusInfo.label}</LemonTag> : null}<LemonTag type="default">@@ -160,47 +172,89 @@ export const NotebookKernelInfo = (): JSX.Element => {<LemonTag type="default">{kernelInfo.disk_size_gb} GB disk</LemonTag>) : null}</div>- <div className="flex items-center gap-2 text-xs">- {isModalKernel ? (- <span className="font-semibold">- {formatHourlyPrice(- selectedCpu * CPU_PRICE_PER_CORE_HOUR +- selectedMemory * MEMORY_PRICE_PER_GIB_HOUR- )}- </span>- ) : null}- </div></div>+ {isModalKernel && selectedHourlyPrice != null ? (+ <div className="flex items-center justify-between text-xs">+ <span className="font-semibold text-muted">Sandbox price</span>+ <Tooltip title={PRICE_TOOLTIP}>+ <span className="font-semibold">{formatHourlyPrice(selectedHourlyPrice)}</span>+ </Tooltip>+ </div>+ ) : null}+ {computeOptionsFailed ? (+ <div className="text-xs text-danger">+ Couldn't load compute rates, so this sandbox can't be sized or started. Refresh to try+ again.+ </div>+ ) : null}{kernelInfo.last_error ? (<div className="text-xs text-danger">Error: {kernelInfo.last_error}</div>) : null}{isModalKernel ? (<div className="space-y-3">+ {computePresets.length ? (+ <div className="space-y-1">+ <div className="text-xs font-semibold text-muted uppercase tracking-wide">+ Presets+ </div>+ <div className="flex flex-col gap-1">+ {computePresets.map((preset) => (+ <LemonButton+ key={preset.key}+ size="small"+ fullWidth+ active={selectedPresetKey === preset.key}+ onClick={() => applyComputePreset(preset)}+ tooltip={preset.description}+ data-attr="notebook-kernel-compute-preset"+ >+ <div className="flex w-full items-center justify-between gap-2 text-xs">+ <span className="truncate">+ <span className="font-semibold">{preset.name}</span>+ <span className="text-muted">+ {' '}+ {formatCores(preset.cpu_cores)} /{' '}+ {formatMemory(preset.memory_gb)}+ </span>+ </span>+ <span className="font-semibold whitespace-nowrap">+ {formatHourlyPrice(preset.hourly_price)}+ </span>+ </div>+ </LemonButton>+ ))}+ </div>+ </div>+ ) : null}<div className="space-y-3"><div className="space-y-1"><div className="flex items-center justify-between text-xs"><span className="font-semibold text-muted">CPU </span>- <span className="font-semibold">{formatCores(selectedCpu)} </span>+ <span className="font-semibold">+ {selectedCpu != null ? formatCores(selectedCpu) : null}{' '}+ </span></div><LemonSlidervalue={cpuIndex}min={0}- max={cpuCoreOptions.length - 1}+ max={cpuOptions.length - 1}step={1}- onChange={(value) => setCpuIndex(value)}+ onChange={(value) => setCpuCores(cpuOptions[value])}/></div><div className="space-y-1"><div className="flex items-center justify-between text-xs"><span className="font-semibold text-muted">RAM</span>- <span className="font-semibold">{formatMemory(selectedMemory)}</span>+ <span className="font-semibold">+ {selectedMemory != null ? formatMemory(selectedMemory) : null}+ </span></div><LemonSlidervalue={memoryIndex}min={0}- max={memoryGbOptions.length - 1}+ max={memoryOptions.length - 1}step={1}- onChange={(value) => setMemoryIndex(value)}+ onChange={(value) => setMemoryGb(memoryOptions[value])}/></div></div>@@ -233,6 +287,7 @@ export const NotebookKernelInfo = (): JSX.Element => {onClick={startOrRestartKernel}loading={startActionInFlight}disabled={hasActionInFlight && !startActionInFlight}+ disabledReason={computeBlockedReason ?? undefined}>{startActionLabel}</LemonButton>diff --git a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.tsindex 71b4803002f4..a397feeb6e10 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts@@ -2,9 +2,29 @@ import api from 'lib/api'import { initKeaTests } from '~/test/init'+import { notebooksKernelComputeOptionsRetrieve } from 'products/notebooks/frontend/generated/api'+import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'import type { NotebookLogicMode } from './notebookLogic'+jest.mock('products/notebooks/frontend/generated/api', () => ({+ notebooksKernelComputeOptionsRetrieve: jest.fn(),+}))++const COMPUTE_OPTIONS = {+ currency: 'USD',+ cpu_rate_per_core_hour: 0.2,+ memory_rate_per_gb_hour: 0.025,+ default_preset_key: 'small',+ presets: [+ { key: 'small', name: 'Small', description: '', cpu_cores: 1, memory_gb: 2, hourly_price: 0.25 },+ { key: 'balanced', name: 'Balanced', description: '', cpu_cores: 4, memory_gb: 8, hourly_price: 1 },+ ],+ allowed_cpu_cores: [1, 2, 4, 8],+ allowed_memory_gb: [2, 4, 8, 16],+ allowed_idle_timeout_seconds: [600, 1800],+}+const setHidden = (hidden: boolean): void => {Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })document.dispatchEvent(new Event('visibilitychange'))@@ -19,6 +39,7 @@ describe('notebookKernelInfoLogic', () => {kernelStatusSpy = jest.spyOn(api.notebooks, 'kernelStatus').mockResolvedValue({ backend: null, status: 'stopped' })+ jest.mocked(notebooksKernelComputeOptionsRetrieve).mockResolvedValue(COMPUTE_OPTIONS)jest.useFakeTimers()})@@ -117,6 +138,114 @@ describe('notebookKernelInfoLogic', () => {expect(kernelStatusSpy).toHaveBeenCalledTimes(callsPerMount - 1)})+ test('a failed options load blocks configuration instead of going quietly unpriced', async () => {+ // The loader's null is also its initial value, so a swallowed failure used to leave the+ // panel looking pre-pricing while Start stayed live.+ jest.mocked(notebooksKernelComputeOptionsRetrieve).mockRejectedValue(new Error('boom'))+ kernelStatusSpy.mockResolvedValue({ backend: 'modal', status: 'stopped', cpu_cores: 1, memory_gb: 2 })+ logic = notebookKernelInfoLogic({ shortId: 'options-fail-01890abc', mode: 'notebook' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.computeOptionsFailed).toBe(true)+ expect(logic.values.computeBlockedReason).not.toBeNull()+ })++ test('Refresh retries the rates after they failed', async () => {+ jest.mocked(notebooksKernelComputeOptionsRetrieve).mockRejectedValueOnce(new Error('boom'))+ logic = notebookKernelInfoLogic({ shortId: 'options-retry-01890abc', mode: 'notebook' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.computeOptions).toBeNull()++ // Refresh reloads both, which is the panel's retry affordance.+ jest.mocked(notebooksKernelComputeOptionsRetrieve).mockResolvedValue(COMPUTE_OPTIONS)+ logic.actions.loadKernelInfo()+ logic.actions.loadComputeOptions()+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.computeOptions).not.toBeNull()+ expect(logic.values.computeBlockedReason).toBeNull()+ })++ test('shows no price at all when the rates are unavailable', async () => {+ // The status endpoint's hourly_price describes the running sandbox, while the sliders+ // show the configured shape. Reusing it here would print a price for a shape that is not+ // on screen, so the panel shows none and blocks configuration instead.+ jest.mocked(notebooksKernelComputeOptionsRetrieve).mockRejectedValue(new Error('boom'))+ kernelStatusSpy.mockResolvedValue({+ backend: 'modal',+ status: 'running',+ cpu_cores: 4,+ memory_gb: 8,+ hourly_price: 1,+ })+ logic = notebookKernelInfoLogic({ shortId: 'no-price-01890abc', mode: 'notebook' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.selectedHourlyPrice).toBeNull()+ expect(logic.values.computeBlockedReason).not.toBeNull()+ })++ test('does not restart again when the server already did', async () => {+ // A resize restarts the kernel server-side. Restarting again would tear down the sandbox+ // that was just built for the new shape.+ const configSpy = jest.spyOn(api.notebooks, 'kernelConfig').mockResolvedValue({ restarted: true })+ const restartSpy = jest.spyOn(api.notebooks, 'kernelRestart').mockResolvedValue({})+ logic = notebookKernelInfoLogic({ shortId: 'no-double-restart-01890abc', mode: 'notebook' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ logic.actions.saveKernelConfig({ cpu_cores: 4, memory_gb: 8 }, 'restart')+ await jest.advanceTimersByTimeAsync(0)++ expect(configSpy).toHaveBeenCalled()+ expect(restartSpy).not.toHaveBeenCalled()+ })++ test('a shared notebook issues no team-scoped kernel requests', async () => {+ // A shared view renders from cachedNotebook so a logged-out viewer makes no team-scoped+ // call. Both kernel endpoints are team-scoped, so mounting here used to 401 twice.+ // The panel is not the only mount: notebookLogic connects this logic for every notebook,+ // and the exporter goes through that path, so isShared has to reach it from there.+ logic = notebookKernelInfoLogic({ shortId: 'shared-01890abc', mode: 'notebook', isShared: true })+ logic.mount()+ await jest.advanceTimersByTimeAsync(30_000)++ expect(kernelStatusSpy).not.toHaveBeenCalled()+ expect(jest.mocked(notebooksKernelComputeOptionsRetrieve)).not.toHaveBeenCalled()+ })++ test('quotes a hand-tuned shape at the rates the API returned', async () => {+ logic = notebookKernelInfoLogic({ shortId: 'pricing-01890abc', mode: 'notebook' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ logic.actions.setCpuCores(8)+ logic.actions.setMemoryGb(16)++ // 8 x $0.20 + 16 x $0.025. A hardcoded rate anywhere in the widget fails here.+ expect(logic.values.selectedHourlyPrice).toBeCloseTo(2.0, 5)+ // No preset has this shape, so nothing should stay highlighted as selected.+ expect(logic.values.selectedPresetKey).toBeNull()+ })++ test('a preset sets both halves of the shape it is priced for', async () => {+ logic = notebookKernelInfoLogic({ shortId: 'preset-01890abc', mode: 'notebook' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ const balanced = logic.values.computePresets.find((preset) => preset.key === 'balanced')!+ logic.actions.applyComputePreset(balanced)++ expect(logic.values.selectedCpu).toBe(balanced.cpu_cores)+ expect(logic.values.selectedMemory).toBe(balanced.memory_gb)+ // The preset's advertised price has to be what the user is then quoted.+ expect(logic.values.selectedHourlyPrice).toBeCloseTo(balanced.hourly_price, 5)+ expect(logic.values.selectedPresetKey).toBe('balanced')+ })+test('stays stopped when the tab returns after the kea store was replaced', async () => {logic = notebookKernelInfoLogic({ shortId: 'hidden-tab-01890abc', mode: 'notebook' })logic.mount()diff --git a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.tsindex b88b305bb3f3..b78b6cdad92f 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts@@ -14,6 +14,13 @@ import {import { loaders } from 'kea-loaders'import api from 'lib/api'+import { ApiConfig } from 'lib/api'++import { notebooksKernelComputeOptionsRetrieve } from 'products/notebooks/frontend/generated/api'+import type {+ NotebookComputeOptionsResponseApi,+ NotebookComputePresetApi,+} from 'products/notebooks/frontend/generated/api.schemas'import { PythonKernelExecuteResponse } from '../Nodes/pythonExecution'import type { NotebookLogicMode } from './notebookLogic'@@ -46,6 +53,10 @@ export type NotebookKernelInfo = {memory_gb?: number | nulldisk_size_gb?: number | nullidle_timeout_seconds?: number | null+ /** What this sandbox shape costs per hour while it is alive, in USD. */+ hourly_price?: number | null+ /** Compute preset the shape matches, or null when it was tuned by hand. */+ preset_key?: string | null}export type NotebookKernelInfoLogicProps = {@@ -57,10 +68,20 @@ export type NotebookKernelInfoLogicProps = {* render one, so polling them costs a 404 every 10 seconds for as long as the page is open.*/mode?: NotebookLogicMode+ /**+ * True on a shared or exported view, which renders from `cachedNotebook` precisely so it+ * issues no team-scoped requests. Both kernel endpoints are team-scoped, so a logged-out+ * viewer would get a 401 from each. Nobody can start a kernel from such a view anyway.+ */+ isShared?: boolean}-export const cpuCoreOptions = [0.125, 0.25, 0.5, 1, 2, 4, 6, 8, 16, 32, 64]-export const memoryGbOptions = [0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256]+/**+ * Sizes the sliders offer before the compute options endpoint answers. That endpoint is the+ * source of truth for both the sizes and the rates, so these only cover the first render.+ */+export const fallbackCpuCoreOptions = [0.125, 0.25, 0.5, 1, 2, 4, 6, 8, 16, 32, 64]+export const fallbackMemoryGbOptions = [0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256]export const idleTimeoutOptions = [{ label: '10 minutes', value: 600 },{ label: '30 minutes', value: 1800 },@@ -97,10 +118,16 @@ const findClosestOptionIndex = (options: number[], value?: number | null): numbeexport interface notebookKernelInfoLogicValues {actionInFlight: KernelActionInFlightcode: string+ computeBlockedReason: 'Compute rates are unavailable. Refresh to try again.' | 'Loading compute rates' | null+ computeOptions: NotebookComputeOptionsResponseApi | null+ computeOptionsFailed: boolean+ computeOptionsLoading: boolean+ computePresets: NotebookComputePresetApi[]cpuIndex: number- currentCpu: number+ cpuOptions: number[]+ currentCpu: number | nullcurrentIdleTimeout: number- currentMemory: number+ currentMemory: number | nullexecutionResult: PythonKernelExecuteResponse | nullexecutionResultLoading: booleanhasActionInFlight: boolean@@ -115,8 +142,11 @@ export interface notebookKernelInfoLogicValues {kernelInfoLoading: booleanlocalFrames: NotebookKernelFrame[]memoryIndex: number- selectedCpu: number- selectedMemory: number+ memoryOptions: number[]+ selectedCpu: number | null+ selectedHourlyPrice: number | null+ selectedMemory: number | null+ selectedPresetKey: string | nullstatusInfo: {label: stringtone: 'danger' | 'default' | 'success' | 'warning'@@ -125,6 +155,9 @@ export interface notebookKernelInfoLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface notebookKernelInfoLogicActions {+ applyComputePreset: (preset: NotebookComputePresetApi) => {+ preset: NotebookComputePresetApi+ }clearExecution: () => {value: true}@@ -149,6 +182,21 @@ export interface notebookKernelInfoLogicActions {code: any}}+ loadComputeOptions: () => any+ loadComputeOptionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadComputeOptionsSuccess: (+ computeOptions: NotebookComputeOptionsResponseApi,+ payload?: any+ ) => {+ computeOptions: NotebookComputeOptionsResponseApi+ payload?: any+ }loadKernelInfo: () => anyloadKernelInfoFailure: (error: string,@@ -191,21 +239,21 @@ export interface notebookKernelInfoLogicActions {setCode: (code: string) => {code: string}- setConfigFromKernelInfo: (config: { cpuIndex: number; idleTimeoutSeconds: number; memoryIndex: number }) => {+ setConfigFromKernelInfo: (config: { cpuCores: number; idleTimeoutSeconds: number; memoryGb: number }) => {config: {- cpuIndex: number+ cpuCores: numberidleTimeoutSeconds: number- memoryIndex: number+ memoryGb: number}}- setCpuIndex: (cpuIndex: number) => {- cpuIndex: number+ setCpuCores: (cpuCores: number) => {+ cpuCores: number}setIdleTimeoutSeconds: (idleTimeoutSeconds: number) => {idleTimeoutSeconds: number}- setMemoryIndex: (memoryIndex: number) => {- memoryIndex: number+ setMemoryGb: (memoryGb: number) => {+ memoryGb: number}startKernel: () => {value: true@@ -232,18 +280,36 @@ export interface notebookKernelInfoLogicMeta {hasActionInFlight: (actionInFlight: KernelActionInFlight) => booleanisModalKernel: (kernelInfo: NotebookKernelInfo | null) => booleanlocalFrames: (kernelInfo: NotebookKernelInfo | null) => NotebookKernelFrame[]- selectedCpu: (cpuIndex: number) => number- selectedMemory: (memoryIndex: number) => number- currentCpu: (kernelInfo: NotebookKernelInfo | null, selectedCpu: number) => number- currentMemory: (kernelInfo: NotebookKernelInfo | null, selectedMemory: number) => number+ cpuOptions: (computeOptions: NotebookComputeOptionsResponseApi | null) => number[]+ memoryOptions: (computeOptions: NotebookComputeOptionsResponseApi | null) => number[]+ computePresets: (computeOptions: NotebookComputeOptionsResponseApi | null) => NotebookComputePresetApi[]+ cpuIndex: (cpuOptions: number[], selectedCpu: number | null) => number+ memoryIndex: (memoryOptions: number[], selectedMemory: number | null) => number+ currentCpu: (kernelInfo: NotebookKernelInfo | null, selectedCpu: number | null) => number | null+ currentMemory: (kernelInfo: NotebookKernelInfo | null, selectedMemory: number | null) => number | null+ selectedHourlyPrice: (+ computeOptions: NotebookComputeOptionsResponseApi | null,+ selectedCpu: number | null,+ selectedMemory: number | null+ ) => number | null+ computeBlockedReason: (+ isModalKernel: boolean,+ computeOptions: NotebookComputeOptionsResponseApi | null,+ computeOptionsLoading: boolean+ ) => 'Compute rates are unavailable. Refresh to try again.' | 'Loading compute rates' | null+ selectedPresetKey: (+ computePresets: NotebookComputePresetApi[],+ selectedCpu: number | null,+ selectedMemory: number | null+ ) => string | nullcurrentIdleTimeout: (kernelInfo: NotebookKernelInfo | null) => numberhasConfigChanges: (kernelInfo: NotebookKernelInfo | null,- selectedCpu: number,- selectedMemory: number,+ selectedCpu: number | null,+ selectedMemory: number | null,idleTimeoutSeconds: number,- currentCpu: number,- currentMemory: number,+ currentCpu: number | null,+ currentMemory: number | null,currentIdleTimeout: number) => boolean}@@ -263,11 +329,12 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([actions({executeKernel: (code) => ({ code }),setCode: (code: string) => ({ code }),- setCpuIndex: (cpuIndex: number) => ({ cpuIndex }),- setMemoryIndex: (memoryIndex: number) => ({ memoryIndex }),+ setCpuCores: (cpuCores: number) => ({ cpuCores }),+ setMemoryGb: (memoryGb: number) => ({ memoryGb }),+ applyComputePreset: (preset: NotebookComputePresetApi) => ({ preset }),setIdleTimeoutSeconds: (idleTimeoutSeconds: number) => ({ idleTimeoutSeconds }),resetConfigToKernel: true,- setConfigFromKernelInfo: (config: { cpuIndex: number; memoryIndex: number; idleTimeoutSeconds: number }) => ({+ setConfigFromKernelInfo: (config: { cpuCores: number; memoryGb: number; idleTimeoutSeconds: number }) => ({config,}),startKernel: true,@@ -290,18 +357,20 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([setCode: (_, { code }) => code,},],- cpuIndex: [- 0,+ selectedCpu: [+ null as number | null,{- setCpuIndex: (_, { cpuIndex }) => cpuIndex,- setConfigFromKernelInfo: (_, { config }) => config.cpuIndex,+ setCpuCores: (_, { cpuCores }) => cpuCores,+ applyComputePreset: (_, { preset }) => preset.cpu_cores,+ setConfigFromKernelInfo: (_, { config }) => config.cpuCores,},],- memoryIndex: [- 0,+ selectedMemory: [+ null as number | null,{- setMemoryIndex: (_, { memoryIndex }) => memoryIndex,- setConfigFromKernelInfo: (_, { config }) => config.memoryIndex,+ setMemoryGb: (_, { memoryGb }) => memoryGb,+ applyComputePreset: (_, { preset }) => preset.memory_gb,+ setConfigFromKernelInfo: (_, { config }) => config.memoryGb,},],idleTimeoutSeconds: [@@ -311,11 +380,20 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([setConfigFromKernelInfo: (_, { config }) => config.idleTimeoutSeconds,},],+ computeOptionsFailed: [+ false,+ {+ loadComputeOptions: () => false,+ loadComputeOptionsSuccess: () => false,+ loadComputeOptionsFailure: () => true,+ },+ ],isEditingConfig: [false,{- setCpuIndex: () => true,- setMemoryIndex: () => true,+ setCpuCores: () => true,+ setMemoryGb: () => true,+ applyComputePreset: () => true,setIdleTimeoutSeconds: () => true,setConfigFromKernelInfo: () => false,resetConfigToKernel: () => false,@@ -362,6 +440,17 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([],}),loaders(({ props }) => ({+ computeOptions: [+ null as NotebookComputeOptionsResponseApi | null,+ {+ // Deliberately unguarded: a swallowed failure is indistinguishable from the+ // null the loader starts with, which left the panel quietly unpriced while+ // every control that spends money stayed live.+ loadComputeOptions: async () => {+ return await notebooksKernelComputeOptionsRetrieve(String(ApiConfig.getCurrentTeamId()))+ },+ },+ ],kernelInfo: [null as NotebookKernelInfo | null,{@@ -445,15 +534,86 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([(kernelInfo: NotebookKernelInfo | null) => kernelInfo?.backend === 'modal',],localFrames: [(s) => [s.kernelInfo], (kernelInfo: NotebookKernelInfo | null) => kernelInfo?.frames ?? []],- selectedCpu: [(s) => [s.cpuIndex], (cpuIndex: number) => cpuCoreOptions[cpuIndex]],- selectedMemory: [(s) => [s.memoryIndex], (memoryIndex: number) => memoryGbOptions[memoryIndex]],+ cpuOptions: [+ (s) => [s.computeOptions],+ (computeOptions: NotebookComputeOptionsResponseApi | null) =>+ computeOptions?.allowed_cpu_cores ?? fallbackCpuCoreOptions,+ ],+ memoryOptions: [+ (s) => [s.computeOptions],+ (computeOptions: NotebookComputeOptionsResponseApi | null) =>+ computeOptions?.allowed_memory_gb ?? fallbackMemoryGbOptions,+ ],+ computePresets: [+ (s) => [s.computeOptions],+ (computeOptions: NotebookComputeOptionsResponseApi | null) => computeOptions?.presets ?? [],+ ],+ cpuIndex: [+ (s) => [s.cpuOptions, s.selectedCpu],+ (cpuOptions: number[], selectedCpu: number | null) => findClosestOptionIndex(cpuOptions, selectedCpu),+ ],+ memoryIndex: [+ (s) => [s.memoryOptions, s.selectedMemory],+ (memoryOptions: number[], selectedMemory: number | null) =>+ findClosestOptionIndex(memoryOptions, selectedMemory),+ ],currentCpu: [(s) => [s.kernelInfo, s.selectedCpu],- (kernelInfo: NotebookKernelInfo | null, selectedCpu: number) => kernelInfo?.cpu_cores ?? selectedCpu,+ (kernelInfo: NotebookKernelInfo | null, selectedCpu: number | null) => kernelInfo?.cpu_cores ?? selectedCpu,],currentMemory: [(s) => [s.kernelInfo, s.selectedMemory],- (kernelInfo: NotebookKernelInfo | null, selectedMemory: number) => kernelInfo?.memory_gb ?? selectedMemory,+ (kernelInfo: NotebookKernelInfo | null, selectedMemory: number | null) =>+ kernelInfo?.memory_gb ?? selectedMemory,+ ],+ /** Price of the shape the user currently has selected, whether they picked it or tuned it. */+ selectedHourlyPrice: [+ (s) => [s.computeOptions, s.selectedCpu, s.selectedMemory],+ (+ computeOptions: NotebookComputeOptionsResponseApi | null,+ selectedCpu: number | null,+ selectedMemory: number | null+ ) => {+ if (selectedCpu == null || selectedMemory == null) {+ return null+ }+ if (computeOptions) {+ return (+ selectedCpu * computeOptions.cpu_rate_per_core_hour ++ selectedMemory * computeOptions.memory_rate_per_gb_hour+ )+ }+ // No fallback to kernelInfo.hourly_price: that prices the sandbox currently+ // running, while cpu_cores and memory_gb describe the configured shape the+ // sliders show. The two differ between a resize and the restart that applies it,+ // so reusing it here would print a price for a shape that is not on screen.+ // Without the rates the panel shows no price and blocks configuration instead.+ return null+ },+ ],+ /**+ * Why compute configuration is blocked, or null when it is allowed. A Modal sandbox is+ * charged, so it may not be started or resized while the rates are unknown.+ */+ computeBlockedReason: [+ (s) => [s.isModalKernel, s.computeOptions, s.computeOptionsLoading],+ (isModalKernel: boolean, computeOptions: NotebookComputeOptionsResponseApi | null, loading: boolean) => {+ if (!isModalKernel || computeOptions) {+ return null+ }+ return loading ? 'Loading compute rates' : 'Compute rates are unavailable. Refresh to try again.'+ },+ ],+ selectedPresetKey: [+ (s) => [s.computePresets, s.selectedCpu, s.selectedMemory],+ (presets: NotebookComputePresetApi[], selectedCpu: number | null, selectedMemory: number | null) =>+ presets.find(+ (preset) =>+ selectedCpu != null &&+ selectedMemory != null &&+ Math.abs(preset.cpu_cores - selectedCpu) < 1e-6 &&+ Math.abs(preset.memory_gb - selectedMemory) < 1e-6+ )?.key ?? null,],currentIdleTimeout: [(s) => [s.kernelInfo],@@ -471,15 +631,19 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([],(kernelInfo: NotebookKernelInfo | null,- selectedCpu: number,- selectedMemory: number,+ selectedCpu: number | null,+ selectedMemory: number | null,idleTimeoutSeconds: number,- currentCpu: number,- currentMemory: number,+ currentCpu: number | null,+ currentMemory: number | null,currentIdleTimeout: number) =>Boolean(kernelInfo &&+ selectedCpu != null &&+ selectedMemory != null &&+ currentCpu != null &&+ currentMemory != null &&(Math.abs(selectedCpu - currentCpu) > 1e-6 ||Math.abs(selectedMemory - currentMemory) > 1e-6 ||idleTimeoutSeconds !== currentIdleTimeout)@@ -509,8 +673,12 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([}},saveKernelConfig: async ({ config, nextAction }) => {+ let restarted = falsetry {- await api.notebooks.kernelConfig(props.shortId, config)+ const response = (await api.notebooks.kernelConfig(props.shortId, config)) as {+ restarted?: boolean+ }+ restarted = response?.restarted ?? false} catch {actions.saveKernelConfigFailure()return@@ -519,6 +687,12 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([actions.startKernel()return}+ // A resize restarts the live kernel server-side. Restarting again would tear down the+ // sandbox that was just built for the new shape.+ if (restarted) {+ actions.loadKernelInfo()+ return+ }actions.restartKernel()},loadKernelInfoSuccess: ({ kernelInfo }) => {@@ -529,8 +703,8 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([return}actions.setConfigFromKernelInfo({- cpuIndex: findClosestOptionIndex(cpuCoreOptions, kernelInfo.cpu_cores),- memoryIndex: findClosestOptionIndex(memoryGbOptions, kernelInfo.memory_gb),+ cpuCores: kernelInfo.cpu_cores ?? values.cpuOptions[0],+ memoryGb: kernelInfo.memory_gb ?? values.memoryOptions[0],idleTimeoutSeconds: kernelInfo.idle_timeout_seconds ?? idleTimeoutOptions[1].value,})},@@ -539,8 +713,8 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([return}actions.setConfigFromKernelInfo({- cpuIndex: findClosestOptionIndex(cpuCoreOptions, values.kernelInfo.cpu_cores),- memoryIndex: findClosestOptionIndex(memoryGbOptions, values.kernelInfo.memory_gb),+ cpuCores: values.kernelInfo.cpu_cores ?? values.cpuOptions[0],+ memoryGb: values.kernelInfo.memory_gb ?? values.memoryOptions[0],idleTimeoutSeconds: values.kernelInfo.idle_timeout_seconds ?? idleTimeoutOptions[1].value,})},@@ -555,7 +729,7 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([},})),afterMount(({ actions, cache, props, values }) => {- if (props.mode && props.mode !== 'notebook') {+ if ((props.mode && props.mode !== 'notebook') || props.isShared) {return}// Replacing the kea context drops this logic's path from the store without unmounting it,@@ -569,6 +743,7 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([const mountedIn = getContext()const isLive = (): boolean => getContext() === mountedInactions.loadKernelInfo()+ actions.loadComputeOptions()cache.disposables.add(() => {// Reschedules itself rather than using setInterval, because a starting kernel is// polled five times more often than a settled one.diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 39795a19c311..370d22f5848d 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -741,7 +741,14 @@ export const notebookLogic = kea<notebookLogicType>([item_id: props.shortId,}),['comments', 'selectedCommentId'],- notebookKernelInfoLogic({ shortId: props.shortId, mode: props.mode }),+ notebookKernelInfoLogic({+ shortId: props.shortId,+ mode: props.mode,+ // A shared view is exactly the one that renders from cachedNotebook, and both kernel+ // endpoints are team-scoped. This is the mount that matters: the panel is not the+ // only thing that brings the logic up.+ isShared: !!props.cachedNotebook,+ }),['kernelInfo'],notebookSettingsLogic,['showKernelInfo', 'showVariablesOverride'],