{"record":{"id":"ab2b86d05304910e","repo":"mastra-ai/mastra","slug":"backgroundtaskworker-call-init-before-start","errorCode":null,"errorMessage":"BackgroundTaskWorker: call init() before start()","messagePattern":"BackgroundTaskWorker: call init\\(\\) before start\\(\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/core/src/worker/workers/background-task-worker.ts","lineNumber":108,"sourceCode":"    for (const [name, tool] of Object.entries(tools)) {\n      if (!tool || typeof tool.execute !== 'function') continue;\n      const execute = tool.execute.bind(tool);\n      this.#manager.registerStaticExecutor(name, {\n        execute: async (args, options) => {\n          return execute(args, {\n            toolCallId: '',\n            messages: [],\n            abortSignal: options?.abortSignal,\n          });\n        },\n      });\n    }\n  }\n\n  async start(): Promise<void> {\n    if (this.#running) return;\n    if (!this.deps) {\n      throw new Error('BackgroundTaskWorker: call init() before start()');\n    }\n    // An owned manager has a terminal shutdown lifecycle. Recreate it on a\n    // direct stop → start cycle instead of attempting to reinitialize a\n    // manager whose subscriptions and executor registry were released.\n    if (!this.#manager) {\n      this.#createOwnedManager(this.deps);\n    }\n    const manager = this.#manager;\n    if (!manager) {\n      throw new Error('BackgroundTaskWorker: failed to initialize background task manager');\n    }\n    // When sharing Mastra's manager, Mastra has already fired off init() in\n    // its constructor as fire-and-forget. Don't re-await it here — that would\n    // surface init errors twice (the constructor's `.catch` already reports\n    // them) and serialize startWorkers() behind the manager's full bootstrap.\n    if (this.#ownsManager) {\n      await manager.init(this.deps.pubsub);\n    }","sourceCodeStart":90,"sourceCodeEnd":126,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/worker/workers/background-task-worker.ts#L90-L126","documentation":"BackgroundTaskWorker follows a two-phase lifecycle: init(deps) injects the worker's dependencies, then start() begins processing. start() refuses to run when deps were never injected, because the worker would have no storage/logger/manager to operate on. It is a fail-fast guard against incorrect lifecycle usage.","triggerScenarios":"Calling worker.start() directly after construction without awaiting worker.init(deps) first, or calling start() before init's promise resolves.","commonSituations":"Bootstrapping a standalone worker in a script or custom server and forgetting the init() call; copying a start-only snippet from docs; race where start() is invoked concurrently with init() before deps are assigned.","solutions":["Call await worker.init(deps) with a valid WorkerDeps object before start()","Ensure init's returned promise is awaited (deps are set synchronously inside init, but sequence the calls anyway)","If embedding in Mastra, register the worker via Mastra's workers config so the framework performs init for you","Double-check ordering in your bootstrap code: constructor → init → start"],"exampleFix":"// before\nconst worker = new BackgroundTaskWorker({ name: 'tasks' });\nawait worker.start();\n// after\nconst worker = new BackgroundTaskWorker({ name: 'tasks' });\nawait worker.init({ mastra, storage, logger, pubsub });\nawait worker.start();","handlingStrategy":"try-catch","validationCode":"if (!worker.deps) await worker.init(deps);","typeGuard":"function isInitialized(worker) { return !!worker.deps; }","tryCatchPattern":"try {\n  if (!worker.deps) await worker.init(deps);\n  await worker.start();\n} catch (e) {\n  if (e.message === 'BackgroundTaskWorker: call init() before start()') {\n    await worker.init(deps);\n    await worker.start();\n  } else throw e;\n}","preventionTips":["Wrap init+start in a single bootstrap helper","Never call start() without awaiting init() first","Prefer Mastra's workers config for framework-managed lifecycle"],"tags":["lifecycle","worker","initialization"],"backgroundTag":"worker-not-initialized","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}