{"record":{"id":"7c0f74210d225c7a","repo":"mastra-ai/mastra","slug":"backgroundtaskmanager-is-shutting-down-cannot-ini","errorCode":null,"errorMessage":"BackgroundTaskManager is shutting down, cannot initialize","messagePattern":"BackgroundTaskManager is shutting down, cannot initialize","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/core/src/background-tasks/manager.ts","lineNumber":104,"sourceCode":"  __registerMastra(mastra: Mastra) {\n    this.#mastra = mastra;\n  }\n\n  async getStorage() {\n    const storage = this.#mastra?.getStorage();\n    if (!storage) {\n      throw new Error('Storage is not initialized');\n    }\n    const bgStore = await storage.getStore('backgroundTasks');\n    if (!bgStore) {\n      throw new Error('Background tasks storage is not available');\n    }\n    return bgStore;\n  }\n\n  async init(pubsub: PubSub): Promise<void> {\n    if (this.shuttingDown) {\n      throw new Error('BackgroundTaskManager is shutting down, cannot initialize');\n    }\n    if (this.initPromise) return this.initPromise;\n    this.initPromise = this.#doInit(pubsub);\n    return this.initPromise;\n  }\n\n  async #doInit(pubsub: PubSub): Promise<void> {\n    this.pubsub = pubsub;\n\n    const isProducerOnly = this.config.mode === 'producer';\n\n    // Result listener: fan-out so all processes receive results.\n    // Both producer and worker modes need this — the producer uses it\n    // to receive completion/failure notifications for dispatched tasks.\n    this.resultCallback = async (event: Event, ack?: () => Promise<void>) => {\n      if (event.type === 'task.completed' || event.type === 'task.failed') {\n        await this.handleResult(event);\n      }","sourceCodeStart":86,"sourceCodeEnd":122,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/background-tasks/manager.ts#L86-L122","documentation":"BackgroundTaskManager.init() refuses to start initialization once shutdown has begun (shuttingDown flag set). This prevents re-subscribing pubsub/workers during or after shutdown, which would leak resources or resurrect a half-torn-down manager. It is a lifecycle-state guard.","triggerScenarios":"Calling init() after shutdown()/graceful shutdown started; a fire-and-forget Mastra init racing an explicit shutdown; restarting tasks programmatically during process termination; test teardown ordering where init runs after shutdown.","commonSituations":"Server SIGTERM handlers calling shutdown while late lazy init fires; hot-reload in dev re-initializing Mastra after shutdown; integration tests that shut down the manager in afterEach while a pending init resolves in the next test.","solutions":["Await init() before initiating shutdown, or skip init if shuttingDown is already true.","Recreate a fresh BackgroundTaskManager instance if you need to run tasks after a shutdown.","Ensure SIGTERM handlers set a flag that gates new init calls, not just enqueue.","Fix test ordering: create a new manager per test instead of re-initializing a shut-down one."],"exampleFix":"// before\nawait manager.shutdown();\nawait manager.init(pubsub); // throws\n// after\nif (!manager.shuttingDown) {\n  await manager.init(pubsub);\n} // or: manager = new BackgroundTaskManager(...); await manager.init(pubsub);","handlingStrategy":"validation","validationCode":"if (manager.shuttingDown) {\n  // skip init or create a fresh manager\n} else {\n  await manager.init(pubsub);\n}","typeGuard":null,"tryCatchPattern":"try {\n  await manager.init(pubsub);\n} catch (e) {\n  if ((e as Error).message.includes('shutting down, cannot initialize')) {\n    manager = new BackgroundTaskManager(...); // fresh instance\n    await manager.init(pubsub);\n  } else throw e;\n}","preventionTips":["Gate init calls on a shutdown flag.","Await init before triggering shutdown paths.","Create a new manager instance for post-shutdown work.","Order test teardown so init never runs after shutdown."],"tags":["background-tasks","lifecycle","shutdown"],"backgroundTag":"manager-already-shutting-down","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}