The code below collects export rows into a temporary file and then moves them to the final path. After a recent PR, the behavior became unstable: with some input data the final file ends up incomplete, and if the asynchronous operation is interrupted, a temporary artifact remains on disk.
ExportRun.finalize() must write all rows from rows in the same order, including empty rows.destination.finalize() is interrupted by task cancellation, the temporary file must not remain open or on disk.rows, including generators.python demo.py
Notice that out.txt loses part of the rows after the first empty string.
Then reproduce cancellation:
import asyncio
from pathlib import Path
from exporter import ExportRun
async def main():
run = ExportRun(Path("cancelled.txt"))
task = asyncio.create_task(run.finalize((str(i) for i in range(1000))))
await asyncio.sleep(0)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
print(run._tmp_path.exists())
asyncio.run(main())
out.txt should contain all input rows, including empty ones.finalize() must not leave an open temporary file or an undeleted temporary path.python demo.py and asyncio.run(...)ExportRun(destination: Path)await ExportRun.finalize(rows: Iterable[str]) -> PathUse line comments to explain the problem, its impact, the fix and how to test it.