{"record":{"id":"c8951240c686574f","repo":"supermemoryai/supermemory","slug":"background-tasks-did-not-complete-within-timeout-c89512","errorCode":null,"errorMessage":"Background tasks did not complete within {timeout}s timeout","messagePattern":"Background tasks did not complete within (.+?)s timeout","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"packages/openai-sdk-python/src/supermemory_openai/middleware.py","lineNumber":557,"sourceCode":"        if not self._background_tasks:\n            return\n\n        self._logger.debug(\n            f\"Waiting for {len(self._background_tasks)} background tasks to complete\"\n        )\n\n        try:\n            if timeout is not None:\n                await asyncio.wait_for(\n                    asyncio.gather(*self._background_tasks, return_exceptions=True),\n                    timeout=timeout,\n                )\n            else:\n                await asyncio.gather(*self._background_tasks, return_exceptions=True)\n\n            self._logger.debug(\"All background tasks completed\")\n        except asyncio.TimeoutError:\n            self._logger.warn(\n                f\"Background tasks did not complete within {timeout}s timeout\"\n            )\n            # Cancel remaining tasks\n            tasks_to_cancel = [task for task in self._background_tasks if not task.done()]\n            for task in tasks_to_cancel:\n                task.cancel()\n\n            if tasks_to_cancel:\n                await asyncio.gather(*tasks_to_cancel, return_exceptions=True)\n            raise\n\n    def cancel_background_tasks(self) -> None:\n        \"\"\"Cancel all pending background tasks.\"\"\"\n        cancelled_count = 0\n        for task in self._background_tasks:\n            if not task.done():\n                task.cancel()\n                cancelled_count += 1","sourceCodeStart":539,"sourceCodeEnd":575,"githubUrl":"https://github.com/supermemoryai/supermemory/blob/d436792e777a99865939dd543c8d1a16d57f54ec/packages/openai-sdk-python/src/supermemory_openai/middleware.py#L539-L575","documentation":"Logged when wait_for_background_tasks times out: memory-save tasks queued in the background (fire-and-forget ingestion) did not finish within the configured timeout (default applied at call site). The middleware cancels all remaining tasks, so those memory writes are abandoned. It is a degradation warning, not a crash.","triggerScenarios":"Exiting the wrapped client's context manager (or calling wait_for_background_tasks(timeout=N)) while slow Supermemory API calls (embeddings, document ingestion) are still in flight; network latency or rate limiting exceeding the timeout; a large batch of create_with_memory calls right before exit.","commonSituations":"Fire-and-forget memory mode with short exit timeouts (5s default in __exit__/__aexit__), slow or rate-limited Supermemory endpoints, high-volume batch jobs that enqueue many saves then close the context, or transient network issues in serverless environments.","solutions":["Increase the timeout: call wait_for_background_tasks(timeout=30) explicitly before exiting the context","Reduce work enqueued right before exit, or flush incrementally during the run","Check Supermemory API latency/rate limits and network connectivity; retry with backoff on the underlying client","Use synchronous (non-background) memory saving if completeness matters more than latency"],"exampleFix":"// before\nasync with client:\n    for m in items:\n        await client.chat.completions.create_with_memory(...)  # 5s exit timeout\n\n// after\nasync with client:\n    for m in items:\n        await client.chat.completions.create_with_memory(...)\n    await client.wait_for_background_tasks(timeout=60.0)","handlingStrategy":"retry","validationCode":"pending = [t for t in client._background_tasks if not t.done()]\nif len(pending) > 20:\n    await client.wait_for_background_tasks(timeout=10)  # drain early","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Drain background tasks periodically instead of only at exit","Set generous timeouts for high-volume sessions","Watch for this warning and correlate with missing memories"],"tags":["python","timeout","background-tasks","memory-save","cancellation"],"backgroundTag":"background-task-timeout","analyzedSha":"d436792e777a99865939dd543c8d1a16d57f54ec","analyzedAt":"2026-08-28T18:04:46.947Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}