{"record":{"id":"5b57af13601a0710","repo":"mastra-ai/mastra","slug":"invalid-state-update-messages","errorCode":null,"errorMessage":"Invalid state update: ${messages}","messagePattern":"Invalid state update: (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/core/src/agent-controller/session.ts","lineNumber":2078,"sourceCode":"          }\n        }\n      }\n    } catch {\n      // Schema doesn't support JSON Schema extraction — skip defaults.\n    }\n\n    return defaults as Partial<TState>;\n  }\n\n  private async apply(updates: Partial<TState>, persistSetting?: PersistSettingFn): Promise<void> {\n    const changedKeys = Object.keys(updates as Record<string, unknown>);\n    const newState = { ...(this.#state as Record<string, unknown>), ...(updates as Record<string, unknown>) };\n\n    if (this.#schema) {\n      const result = await this.#schema['~standard'].validate(newState);\n      if (result.issues) {\n        const messages = result.issues.map(i => i.message).join('; ');\n        throw new Error(`Invalid state update: ${messages}`);\n      }\n      this.#state = result.value as TState;\n    } else {\n      this.#state = newState as TState;\n    }\n\n    this.#bus.emit({ type: 'state_changed', state: this.get() as Record<string, unknown>, changedKeys });\n\n    // Mirror restart-surviving preferences into thread metadata so they can be\n    // restored by `Session.loadMetadata()` after the host process restarts.\n    // Persistence failures never fail the in-memory state update.\n    if (persistSetting) {\n      const state = this.#state as Record<string, unknown>;\n      for (const key of PERSISTED_STATE_KEYS) {\n        if (!changedKeys.includes(key)) continue;\n        try {\n          await persistSetting({ key, value: state[key] });\n        } catch {","sourceCodeStart":2060,"sourceCodeEnd":2096,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/agent-controller/session.ts#L2060-L2096","documentation":"State updates are merged with the current state and validated against the state's Standard Schema when one is configured. If validation produces issues, the library throws with the joined issue messages, and the state is left unchanged — guaranteeing #state always satisfies the schema.","triggerScenarios":"Calling update({ ... }) with values violating the schema (wrong types, missing required fields after merge, invalid enum values, cross-field invariant violations).","commonSituations":"Passing partial updates where the schema requires the merged result to be complete; string/number confusion (e.g. count: '3'); nulling a required field; schema tightened in an upgrade so previously-legal updates now fail.","solutions":["Read the thrown messages to see which schema issues fired and fix the update payload accordingly.","Validate the merged object yourself with the same schema before calling update.","If a required field is only known later, make it optional/nullable in the schema or supply a default in the update."],"exampleFix":"// before\nawait state.update({ count: '3' }); // Invalid state update: expected number\n// after\nconst result = schema['~standard'].validate({ ...state.get(), count: 3 });\nif (!result.issues) await state.update({ count: 3 });","handlingStrategy":"validation","validationCode":"const merged = { ...state.get(), ...updates };\nconst result = stateSchema['~standard'].validate(merged);\nif (result.issues) throw new Error(result.issues.map(i => i.message).join('; '));","typeGuard":null,"tryCatchPattern":"try {\n  await state.update(updates);\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith('Invalid state update: ')) {\n    // parse e.message for issue details; fix payload or reset state\n  } else throw e;\n}","preventionTips":["Pre-validate merged state with the same schema before update","Type updates strictly (z.infer / Input types) to catch mistakes at compile time","Keep schema and update call sites in sync when the schema evolves","Include all required fields in updates when the schema requires a complete object"],"tags":["validation","schema","state"],"backgroundTag":"schema-validation-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}