{"record":{"id":"74f0631bba8508cf","repo":"supermemoryai/supermemory","slug":"some-background-memory-tasks-did-not-complete-on-e","errorCode":null,"errorMessage":"Some background memory tasks did not complete on exit","messagePattern":"Some background memory tasks did not complete on exit","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"packages/openai-sdk-python/src/supermemory_openai/middleware.py","lineNumber":589,"sourceCode":"        cancelled_count = 0\n        for task in self._background_tasks:\n            if not task.done():\n                task.cancel()\n                cancelled_count += 1\n\n        if cancelled_count > 0:\n            self._logger.debug(f\"Cancelled {cancelled_count} pending background tasks\")\n\n    async def __aenter__(self):\n        \"\"\"Async context manager entry.\"\"\"\n        return self\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        \"\"\"Async context manager exit - wait for background tasks.\"\"\"\n        try:\n            await self.wait_for_background_tasks(timeout=5.0)\n        except asyncio.TimeoutError:\n            self._logger.warn(\"Some background memory tasks did not complete on exit\")\n\n    def __enter__(self):\n        \"\"\"Sync context manager entry.\"\"\"\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        \"\"\"Sync context manager exit - attempt to wait for background tasks.\"\"\"\n        if self._background_tasks:\n            try:\n                # Try to wait for background tasks in sync context\n                asyncio.run(self.wait_for_background_tasks(timeout=5.0))\n            except RuntimeError as e:\n                if \"cannot be called from a running event loop\" in str(e):\n                    # In async context, just cancel the tasks\n                    self._logger.warn(\n                        \"Cannot wait for background tasks in sync context from async environment. \"\n                        \"Use async context manager or call wait_for_background_tasks() manually.\"\n                    )","sourceCodeStart":571,"sourceCodeEnd":607,"githubUrl":"https://github.com/supermemoryai/supermemory/blob/d436792e777a99865939dd543c8d1a16d57f54ec/packages/openai-sdk-python/src/supermemory_openai/middleware.py#L571-L607","documentation":"Logged in the async context manager's __aexit__ when waiting for pending background memory tasks exceeds the hardcoded 5-second timeout. Remaining tasks are cancelled, so unsaved memories from those tasks are dropped. It signals the fire-and-forget pipeline could not drain in time during cleanup.","triggerScenarios":"Using 'async with wrapped_client:' and exiting while background memory saves (embeddings, HTTP ingestion calls) are still running longer than 5s; slow network, cold-start latency, or many queued saves at exit.","commonSituations":"Serverless/Lambda handlers wrapping the client in an async context manager per request, batch scripts that finish quickly but leave slow ingestion behind, environments with throttled Supermemory API access.","solutions":["Before exiting the context, await client.wait_for_background_tasks(timeout=30) with a larger timeout to drain tasks","Lower the number of background saves per session or batch them","Investigate slow Supermemory API responses (network, auth tenant throttling) and add retries to the underlying HTTP client","Consider disabling background mode so saves are awaited inline and failures surface immediately"],"exampleFix":"# before\nasync with client:\n    await do_work(client)  # exit gives tasks only 5s\n\n# after\nasync with client:\n    await do_work(client)\n    await client.wait_for_background_tasks(timeout=60.0)","handlingStrategy":"fallback","validationCode":"if client._background_tasks:\n    await client.wait_for_background_tasks(timeout=60.0)  # before exiting 'async with'","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Await wait_for_background_tasks with a large timeout before context exit","Avoid enqueuing many saves immediately before exiting the context","Use synchronous saving when every memory must persist"],"tags":["python","async","timeout","context-manager","background-tasks"],"backgroundTag":"background-task-timeout","analyzedSha":"d436792e777a99865939dd543c8d1a16d57f54ec","analyzedAt":"2026-08-28T18:04:46.947Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}