From 52d4660ae9b098e2dac27c135a4c67c7d1d9c0af Mon Sep 17 00:00:00 2001 From: Xu Han Date: Thu, 11 Sep 2025 06:22:18 +0000 Subject: [PATCH] [AOTI] Fix Windows fail to zip opened file. (#162617) Original issue: Image reproducer: ```cmd pytest test\inductor\test_aot_inductor.py -v -k test_weight_on_disk_legacy_cpu ``` Fixed list: 1. `WritableTempFile`'s `__exit__` function auto unlink opened file, when the file was opened, it should raise error. Ignore it on Windows. 2. When open zip file, if the file is opened, it would be failed. Switch to `_wfsopen` with shared access flag, which can open file with shared access. Local test passed: image Pull Request resolved: https://github.com/pytorch/pytorch/pull/162617 Approved by: https://github.com/jansel --- third_party/miniz-3.0.2/miniz.c | 9 ++++++--- torch/_inductor/codecache.py | 9 ++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/third_party/miniz-3.0.2/miniz.c b/third_party/miniz-3.0.2/miniz.c index bd6b9f856225..0f0cf1833b6d 100644 --- a/third_party/miniz-3.0.2/miniz.c +++ b/third_party/miniz-3.0.2/miniz.c @@ -3136,6 +3136,7 @@ extern "C" { #define WIN32_LEAN_AND_MEAN #include +#include static WCHAR* mz_utf8z_to_widechar(const char* str) { @@ -3149,11 +3150,13 @@ static FILE *mz_fopen(const char *pFilename, const char *pMode) { WCHAR* wFilename = mz_utf8z_to_widechar(pFilename); WCHAR* wMode = mz_utf8z_to_widechar(pMode); - FILE* pFile = NULL; - errno_t err = _wfopen_s(&pFile, wFilename, wMode); + /* + Must use _wfsopen with _SH_DENYNO on Windows, to open opened temp files. + */ + FILE* pFile = _wfsopen(wFilename, wMode, _SH_DENYNO); free(wFilename); free(wMode); - return err ? NULL : pFile; + return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) diff --git a/torch/_inductor/codecache.py b/torch/_inductor/codecache.py index 7b24208a2c51..cda24724575e 100644 --- a/torch/_inductor/codecache.py +++ b/torch/_inductor/codecache.py @@ -390,7 +390,14 @@ class WritableTempFile: def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: self.temp_file.close() - os.unlink(self.temp_file.name) + try: + os.unlink(self.temp_file.name) + except OSError as e: + if _IS_WINDOWS: + # On Windows, some case temp file is opened and fail to unlink. Need to ignore it. + pass + else: + raise e def write(