The code below relates to a small utility that collects background task results in memory and then asynchronously flushes them to a file. After a recent change, the behavior became unstable: some scenarios do not finish correctly, and subsequent calls sometimes operate on an unexpected state.
flush() method must write all elements from pending to the file, one per line.flush(), the pending list of the current instance must become empty.JobCache instances must not share accumulated elements.flush(), the already opened file resource must still be released.JobCache instances without explicitly passing pending.flush() as an asyncio.Task and cancel it after writing has already begun but before the method completes.Example run:
python -m pytest
JobCache instance starts with its own empty pending list.flush() does not leave an open file in self._handle.flush() call after cancellation does not rely on an already closed or "dangling" file object.pytest 8.2.2asyncioopen(..., "w", encoding="utf-8")Use line comments to explain the problem, its impact, the fix and how to test it.