: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(posthog ai): stop core memory exceeding its own character cap (#79958)
posthog[bot]0a126d1607d1
diff --git a/ee/models/test/test_assistant.py b/ee/models/test/test_assistant.pyindex 6db324876793..8161da8ca0b0 100644--- a/ee/models/test/test_assistant.py+++ b/ee/models/test/test_assistant.py@@ -84,6 +84,12 @@ class TestCoreMemory(BaseTest):with self.assertRaises(ValueError):await self.core_memory.areplace_core_memory("nonexistent", "new")+ async def test_set_truncates_at_limit(self):+ await self.core_memory.aset_core_memory("x" * (CORE_MEMORY_MAX_CHARACTERS + 5546))+ self.assertEqual(len(self.core_memory.text), CORE_MEMORY_MAX_CHARACTERS)+ await self.core_memory.arefresh_from_db()+ self.assertEqual(len(self.core_memory.text), CORE_MEMORY_MAX_CHARACTERS)+async def test_append_exceeds_limit(self):await self.core_memory.aset_core_memory("x" * (CORE_MEMORY_MAX_CHARACTERS - 5))with self.assertRaises(ValueError) as ctx:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 3f96c93e4d81..6e5ce7da0bb0 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -66,6 +66,8 @@ const ERROR_FILTER_ALLOW_LIST = ['loadRunDetails', // The Wizard run drawer shows a stale-state banner with a retry'cancelRunRequest', // wizardRunDetailsLogic shows its own cancel-failure toast'loadReplayComments', // The replay Comments tab renders its own retry state+ 'loadCoreMemory', // The PostHog AI memory setting renders its own load error banner with a retry+ 'updateCoreMemory', // maxSettingsLogic's updateCoreMemoryFailure listener shows its own save-failure toast]/*diff --git a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsxindex 00debf8f8fce..78cfe92a2c8b 100644--- a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx+++ b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx@@ -26,7 +26,7 @@ export function SidebarQuestionInputWithSuggestions({const { dataProcessingAccepted, dataProcessingApprovalDisabledReason, activeSuggestionGroup } = useValues(maxLogic)const { setActiveGroup, setFillInHint, runSuggestion } = useActions(maxLogic)const { agentMode } = useValues(maxThreadLogic)- const { coreMemory, coreMemoryLoading } = useValues(maxSettingsLogic)+ const { coreMemory, coreMemoryLoading, coreMemoryLoadError } = useValues(maxSettingsLogic)const [settingsModalOpen, setSettingsModalOpen] = useState(false)const [selectedTopic, setSelectedTopic] = useState<string | null>(null)@@ -39,12 +39,13 @@ export function SidebarQuestionInputWithSuggestions({const showBadges = agentMode !== AgentMode.Researchconst selectedTopicData = HOMEPAGE_SUGGESTION_TOPICS.find((topic) => topic.key === selectedTopic) ?? null- const tip =- !coreMemoryLoading && !coreMemory?.text- ? 'Tip: Run /init to initialize PostHog AI in this project'- : agentMode === AgentMode.Research- ? 'Try PostHog AI Research Mode for…'- : 'Try PostHog AI for…'+ const tip = coreMemoryLoadError+ ? "Could not load PostHog AI's memory. Retry in project settings."+ : !coreMemoryLoading && !coreMemory?.text+ ? 'Tip: Run /init to initialize PostHog AI in this project'+ : agentMode === AgentMode.Research+ ? 'Try PostHog AI Research Mode for…'+ : 'Try PostHog AI for…'return (<DismissableLayerdiff --git a/frontend/src/scenes/settings/environment/MaxMemorySettings.tsx b/frontend/src/scenes/settings/environment/MaxMemorySettings.tsxindex 41727986de73..a444ba6544d6 100644--- a/frontend/src/scenes/settings/environment/MaxMemorySettings.tsx+++ b/frontend/src/scenes/settings/environment/MaxMemorySettings.tsx@@ -1,18 +1,19 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'-import { LemonButton, LemonSkeleton, LemonTextArea } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonSkeleton, LemonTextArea } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'import { TeamMembershipLevel } from 'lib/constants'import { LemonField } from 'lib/lemon-ui/LemonField'import { projectLogic } from 'scenes/projectLogic'-import { maxSettingsLogic } from './maxSettingsLogic'+import { CORE_MEMORY_MAX_CHARACTERS, maxSettingsLogic } from './maxSettingsLogic'export function MaxMemorySettings(): JSX.Element {const { currentProject, currentProjectLoading } = useValues(projectLogic)- const { isLoading, isUpdating } = useValues(maxSettingsLogic)+ const { isLoading, isUpdating, coreMemoryLoadError, coreMemoryOverLimit } = useValues(maxSettingsLogic)+ const { loadCoreMemory, trimCoreMemoryToFit } = useActions(maxSettingsLogic)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,@@ -27,30 +28,64 @@ export function MaxMemorySettings(): JSX.Element {><p className="max-w-160 text-sm text-secondary mb-4">When memory exceeds 5,000 characters, only the first and last 2,500 characters are visible to PostHog- AI. The maximum memory size is 10,000 characters.+ AI. The maximum memory size is {CORE_MEMORY_MAX_CHARACTERS.toLocaleString()} characters.</p>{currentProjectLoading || isLoading ? (<div className="gap-2 flex flex-col"><LemonSkeleton className="h-6 w-32" /><LemonSkeleton className="h-16" /></div>+ ) : coreMemoryLoadError ? (+ <LemonBanner+ type="error"+ action={{ children: 'Retry', onClick: () => loadCoreMemory() }}+ className="max-w-160"+ >+ Could not load PostHog AI's memory. This does not mean your memory is empty. Your saved memory is+ safe. {coreMemoryLoadError}+ </LemonBanner>) : (- <LemonField name="text" label="PostHog AI's memory">- <LemonTextArea- id="product-description-textarea" // Slightly dirty ID for .focus() elsewhere- placeholder={`What should PostHog AI know about ${- currentProject ? currentProject.name : 'your company or this product'- }?`}- maxLength={10000}- maxRows={5}- disabled={!!restrictedReason}- />- </LemonField>+ <>+ {coreMemoryOverLimit && (+ <LemonBanner+ type="warning"+ action={{+ children: 'Trim to fit',+ onClick: () => trimCoreMemoryToFit(),+ disabledReason: restrictedReason,+ }}+ className="max-w-160"+ >+ This memory is over the {CORE_MEMORY_MAX_CHARACTERS.toLocaleString()}-character limit and+ can't be saved until it fits. Trimming keeps the first{' '}+ {CORE_MEMORY_MAX_CHARACTERS.toLocaleString()} characters.+ </LemonBanner>+ )}+ <LemonField name="text" label="PostHog AI's memory">+ <LemonTextArea+ id="product-description-textarea" // Slightly dirty ID for .focus() elsewhere+ placeholder={`What should PostHog AI know about ${+ currentProject ? currentProject.name : 'your company or this product'+ }?`}+ maxLength={CORE_MEMORY_MAX_CHARACTERS}+ maxRows={5}+ disabled={!!restrictedReason}+ />+ </LemonField>+ </>)}<LemonButtontype="primary"htmlType="submit"- disabledReason={!currentProject || isLoading ? 'Loading project and memory...' : restrictedReason}+ disabledReason={+ !currentProject || isLoading+ ? 'Loading project and memory...'+ : coreMemoryLoadError+ ? 'Memory could not be loaded'+ : coreMemoryOverLimit+ ? 'Memory is over the character limit. Trim it to fit first.'+ : restrictedReason+ }loading={isUpdating}>Save memorydiff --git a/frontend/src/scenes/settings/environment/maxSettingsLogic.test.ts b/frontend/src/scenes/settings/environment/maxSettingsLogic.test.tsindex 72ab013ab9ed..0fb85447d6b3 100644--- a/frontend/src/scenes/settings/environment/maxSettingsLogic.test.ts+++ b/frontend/src/scenes/settings/environment/maxSettingsLogic.test.ts@@ -1,7 +1,5 @@import { expectLogic } from 'kea-test-utils'-import api from 'lib/api'-import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -38,8 +36,9 @@ describe('maxSettingsLogic', () => {})it.each([403, 408, 502, 504])(- 'falls back to null without throwing when the load responds with %s',+ 'surfaces a load error instead of masquerading as empty memory when the load responds with %s',async (status) => {+ silenceKeaLoadersErrors()useMocks({get: {'/api/environments/:team_id/core_memory/': () => [status, { detail: 'nope' }],@@ -48,24 +47,32 @@ describe('maxSettingsLogic', () => {logic = maxSettingsLogic()logic.mount()- // The loader catches non-OK responses so they resolve as success with a null value,- // rather than bubbling up as an uncaught frontend error.+ // A failed load must not read as empty memory: it dispatches a failure and populates the+ // error state so the UI can show a retry, not a blank editable textarea.await expectLogic(logic)- .toDispatchActions(['loadCoreMemorySuccess'])- .toNotHaveDispatchedActions(['loadCoreMemoryFailure'])+ .toDispatchActions(['loadCoreMemoryFailure']).toMatchValues({ coreMemory: null, isLoading: false })+ expect(logic.values.coreMemoryLoadError).toBeTruthy()})- it('lets non-HTTP errors propagate so real regressions stay visible', async () => {- silenceKeaLoadersErrors()- // A programming error (not an ApiError) should surface as a failure, not be silently swallowed.- jest.spyOn(api.coreMemory, 'list').mockRejectedValueOnce(new TypeError('boom'))+ it('flags text over the character limit as over the limit', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/core_memory/': () => [+ 200,+ { results: [{ id: 'mem-1', text: 'x'.repeat(15546) }] },+ ],+ },+ })logic = maxSettingsLogic()logic.mount()- await expectLogic(logic)- .toDispatchActions(['loadCoreMemoryFailure'])- .toMatchValues({ coreMemory: null, isLoading: false })+ await expectLogic(logic).toDispatchActions(['loadCoreMemorySuccess', 'setCoreMemoryFormValue'])+ expect(logic.values.coreMemoryOverLimit).toBe(true)++ logic.actions.trimCoreMemoryToFit()+ expect(logic.values.coreMemoryForm.text).toHaveLength(10000)+ expect(logic.values.coreMemoryOverLimit).toBe(false)})})diff --git a/frontend/src/scenes/settings/environment/maxSettingsLogic.tsx b/frontend/src/scenes/settings/environment/maxSettingsLogic.tsxindex c7ed7690d9b9..90a29dae3454 100644--- a/frontend/src/scenes/settings/environment/maxSettingsLogic.tsx+++ b/frontend/src/scenes/settings/environment/maxSettingsLogic.tsx@@ -1,14 +1,17 @@-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import api from 'lib/api'-import { ApiError } from 'lib/api-error'+import { ApiError, isAccessDeniedError } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { CoreMemory } from '~/types'+export const CORE_MEMORY_MAX_CHARACTERS = 10000+export type CoreMemoryForm = {text: string}@@ -25,7 +28,9 @@ export interface maxSettingsLogicValues {coreMemoryFormTouched: booleancoreMemoryFormTouches: Record<string, boolean>coreMemoryFormValidationErrors: DeepPartialMap<CoreMemoryForm, ValidationErrorType>+ coreMemoryLoadError: string | nullcoreMemoryLoading: boolean+ coreMemoryOverLimit: booleanisCoreMemoryFormSubmitting: booleanisCoreMemoryFormValid: booleanisLoading: boolean@@ -88,6 +93,9 @@ export interface maxSettingsLogicActions {touchCoreMemoryFormField: (key: string) => {key: string}+ trimCoreMemoryToFit: () => {+ value: true+ }updateCoreMemory: (data: CoreMemoryForm) => CoreMemoryFormupdateCoreMemoryFailure: (error: string,@@ -105,13 +113,26 @@ export interface maxSettingsLogicActions {}}-export type maxSettingsLogicType = MakeLogicType<maxSettingsLogicValues, maxSettingsLogicActions>+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface maxSettingsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ coreMemoryOverLimit: (coreMemoryForm: CoreMemoryForm) => boolean+ }+}++export type maxSettingsLogicType = MakeLogicType<+ maxSettingsLogicValues,+ maxSettingsLogicActions,+ Record<string, any>,+ maxSettingsLogicMeta+>export const maxSettingsLogic = kea<maxSettingsLogicType>([path(['scenes', 'project', 'Settings', 'maxSettingsLogic']),actions({setIsLoading: (isLoading: boolean) => ({ isLoading }),+ trimCoreMemoryToFit: true,}),reducers({@@ -124,6 +145,15 @@ export const maxSettingsLogic = kea<maxSettingsLogicType>([},],+ coreMemoryLoadError: [+ null as string | null,+ {+ loadCoreMemory: () => null,+ loadCoreMemorySuccess: () => null,+ loadCoreMemoryFailure: (_, { error }) => error || 'Could not load memory.',+ },+ ],+isUpdating: [false,{@@ -141,28 +171,23 @@ export const maxSettingsLogic = kea<maxSettingsLogicType>([coreMemory: {__default: null as CoreMemory | null,loadCoreMemory: async (): Promise<CoreMemory | null> => {- try {- const response = await api.coreMemory.list()- return response.results[0] || null- } catch (error) {- // Non-OK responses (e.g. 403 when lacking access to the environment, or upstream- // timeouts) shouldn't surface as uncaught frontend errors — fall back to empty state.- // Anything that isn't an HTTP error (a real regression in the API client) still propagates.- if (error instanceof ApiError) {- return null- }- throw error- }+ // Let HTTP errors (403, timeout) reach loadCoreMemoryFailure so the UI can show a real+ // error with a retry, rather than an empty textarea that reads as "my memory is gone".+ // An empty result list is a genuine "no memory yet" state and still resolves to null.+ const response = await api.coreMemory.list()+ return response.results[0] || null},updateCoreMemory: async (data: CoreMemoryForm) => {if (!values.coreMemory) {const response = await api.coreMemory.create(data)lemonToast.success('PostHog AI memory has been created.')+ posthog.capture('core memory saved', { action: 'create', length: data.text.length })return response}const response = await api.coreMemory.update(values.coreMemory.id, data)lemonToast.success('PostHog AI memory has been updated.')+ posthog.capture('core memory saved', { action: 'update', length: data.text.length })return response},},@@ -177,12 +202,38 @@ export const maxSettingsLogic = kea<maxSettingsLogicType>([},})),- listeners(({ actions }) => ({+ selectors({+ coreMemoryOverLimit: [+ (s) => [s.coreMemoryForm],+ (coreMemoryForm: CoreMemoryForm) => (coreMemoryForm?.text?.length ?? 0) > CORE_MEMORY_MAX_CHARACTERS,+ ],+ }),++ listeners(({ actions, values }) => ({loadCoreMemorySuccess: ({ coreMemory }) => {if (coreMemory) {actions.setCoreMemoryFormValue('text', coreMemory.text)}},+ loadCoreMemoryFailure: ({ errorObject }) => {+ posthog.capture('core memory load failed', {+ status: errorObject instanceof ApiError ? errorObject.status : undefined,+ access_denied: errorObject instanceof ApiError ? isAccessDeniedError(errorObject) : undefined,+ })+ },+ trimCoreMemoryToFit: () => {+ const trimmed = (values.coreMemoryForm?.text ?? '').slice(0, CORE_MEMORY_MAX_CHARACTERS)+ actions.setCoreMemoryFormValue('text', trimmed)+ posthog.capture('core memory trimmed to fit', { length: trimmed.length })+ },+ updateCoreMemoryFailure: ({ error, errorObject }) => {+ const detail = errorObject instanceof ApiError ? errorObject.detail : null+ lemonToast.error(detail || error || 'Could not save memory.')+ posthog.capture('core memory save failed', {+ status: errorObject instanceof ApiError ? errorObject.status : undefined,+ over_limit: values.coreMemoryOverLimit,+ })+ },})),afterMount(({ actions }) => {diff --git a/products/posthog_ai/backend/models/assistant.py b/products/posthog_ai/backend/models/assistant.pyindex 4f11df4ccd55..4a016b5fa67d 100644--- a/products/posthog_ai/backend/models/assistant.py+++ b/products/posthog_ai/backend/models/assistant.py@@ -6,10 +6,14 @@ from typing import TYPE_CHECKING, Optionalfrom django.db import IntegrityError, modelsfrom django.utils import timezone+import structlog+from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDModel, UUIDTModel+logger = structlog.get_logger(__name__)+if TYPE_CHECKING:from products.tasks.backend.models import TaskRun@@ -286,6 +290,18 @@ class CoreMemory(UUIDTModel):await self.asave()async def aset_core_memory(self, text: str) -> None:+ # Unlike append/replace, this path is fed raw model output (onboarding compression), so it clamps+ # to the cap instead of rejecting. That keeps the stored row within the limit that the serializer,+ # the textarea, and the /remember command all enforce, because an over-cap row can afterwards be+ # neither saved nor edited through any of them.+ if len(text) > CORE_MEMORY_MAX_CHARACTERS:+ logger.warning(+ "core_memory_set_truncated",+ team_id=self.team_id,+ length=len(text),+ limit=CORE_MEMORY_MAX_CHARACTERS,+ )+ text = text[:CORE_MEMORY_MAX_CHARACTERS]self.text = textself.scraping_status = CoreMemory.ScrapingStatus.COMPLETEDawait self.asave()