Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(runio): on Windows the lock entry is made without following a link at its name — os.open's O_CREAT|O_EXCL there is CreateFileW CREATE_NEW, which follows a link to a missing file and makes that file outside the run dir, and ends a folder in EACCES and a link it cannot read in EINVAL instead of the named refusal; _make_entry calls CreateFileW with FILE_FLAG_OPEN_REPARSE_POINT, so any link at the name is ERROR_FILE_EXISTS, reads ERROR_ACCESS_DENIED as a taken name only when lstat finds something other than a file there (a folder, a folder link, a junction) and otherwise raises it, and hands the handle (not inheritable, write only) to a binary descriptor, closing it when it cannot; POSIX keeps the same os.open; the descriptor is tested against os.open's, and the Windows-only handle case is named in NOT_RIFE_SKIPS
Soohong Kim92f2e675131a
diff --git a/sprite_gen/spec/runio.py b/sprite_gen/spec/runio.pyindex 79b3fbc..b5cec4a 100644--- a/sprite_gen/spec/runio.py+++ b/sprite_gen/spec/runio.py@@ -130,6 +130,14 @@ if fcntl is None and os.name == "nt": # pragma: no cover - Windows-only backend_OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]_SYNCHRONIZE, _WAIT_SIGNALED, _WAIT_TIMEOUT = 0x00100000, 0x00000000, 0x00000102_ERROR_ACCESS_DENIED, _ERROR_INVALID_PARAMETER = 5, 87+ # 락 항목은 이름에 놓인 링크를 따라가지 않고 만든다(`_make_entry`) — 이름 자체를 여는 FILE_FLAG_OPEN_REPARSE_POINT+ _CreateFileW = _kernel32.CreateFileW+ _CreateFileW.restype = wintypes.HANDLE+ _CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD,+ wintypes.DWORD, wintypes.HANDLE]+ _GENERIC_WRITE, _FILE_SHARE_READ_WRITE, _CREATE_NEW = 0x40000000, 0x00000001 | 0x00000002, 1+ _FILE_ATTRIBUTE_NORMAL, _FILE_FLAG_OPEN_REPARSE_POINT = 0x00000080, 0x00200000+ _INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value_LOCK_IMPL = "LockFileEx"except (ImportError, OSError, AttributeError):_LOCK_IMPL = None@@ -477,6 +485,38 @@ def _read_entry(lock_path: Path) -> tuple[_LockEntry | None, float]:return _LockEntry(got.st_dev, got.st_ino, b"".join(chunks)), got.st_mtime+def _make_entry(lock_path: Path) -> int:+ """락 이름에 새 일반 파일을 만들어 쓰기 fd 를 돌려준다 — 이름에 무엇이 있으면(링크·폴더도) 따라가지도 만들지도 않고+ FileExistsError. POSIX 는 O_CREAT|O_EXCL 이고 open(2) 은 이름의 링크를 따라가지 않는다. Windows 의 os.open 은 같은 플래그를+ CreateFileW 의 CREATE_NEW 로 넘기는데, 없는 이름에 닿는 링크는 따라가 그 자리에 파일을 만들고, 대상 글자를 읽을 수 없는+ 링크(`/` 로 적힌 대상)는 EINVAL, 폴더는 EACCES 로 끝난다. 그래서 CreateFileW 를 FILE_FLAG_OPEN_REPARSE_POINT 로 불러 이름+ 자체를 연다 — 링크는 어떤 것이든 ERROR_FILE_EXISTS 다. 폴더(폴더 링크·junction 도)는 그래도 ERROR_ACCESS_DENIED 라, 그+ 이름에 일반 파일이 아닌 항목이 정말 있을 때만 FileExistsError 로 읽고 아니면(런 폴더에 쓸 수 없다) 그 오류 그대로다. 핸들은+ os.open 의 fd 처럼 상속되지 않고(보안 속성 없음) 쓰기만 되며, 바이너리 fd 로 넘긴다. 넘기지 못하면 핸들을 닫고 그 오류다 —+ 만든 빈 항목은 os.fstat 이 실패할 때처럼 남는다(주인을 확인할 수 없는 락)."""+ if os.name == "nt": # pragma: no cover - Windows-only backend+ handle = _CreateFileW(str(lock_path), _GENERIC_WRITE, _FILE_SHARE_READ_WRITE, None, _CREATE_NEW,+ _FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT, None)+ if handle == _INVALID_HANDLE_VALUE:+ error = ctypes.get_last_error()+ failed = OSError(0, ctypes.FormatError(error), str(lock_path), error) # winerror 로 errno 와 하위 클래스가 정해진다+ if error == _ERROR_ACCESS_DENIED:+ try:+ taken = not stat.S_ISREG(os.lstat(lock_path).st_mode)+ except OSError:+ taken = False+ if taken:+ raise FileExistsError(errno.EEXIST, "the lock name is not a file (a folder or a link)",+ str(lock_path)) from failed+ raise failed+ try:+ return msvcrt.open_osfhandle(handle, 0) # O_TEXT 가 없으면 바이너리, 접근은 핸들의 것(쓰기)+ except BaseException:+ _CloseHandle(handle)+ raise+ return os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0))++def _remove_if_same(lock_path: Path, entry: _LockEntry, by: int) -> bool:"""락 이름에 있는 것이 `entry` — 프로세스 `by` 가 만들었거나 회수하려고 판정한 바로 그 항목(일반 파일, 같은 장치·inode,같은 내용)이고 `by` 가 지금 이 프로세스일 때만 지운다. 부모의 기록을 물려받은 fork 자식은(파이썬 fork 훅을 거치지 않는@@ -573,8 +613,8 @@ def acquire_run_dir_lock(run_dir: Path, owner: str) -> Path:me = os.getpid()with _entry_guard(lock_path.parent):for _ in range(_LOCK_ROUNDS):- try: # never follows a link at the name (open(2))- fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0))+ try: # never follows a link at the name (`_make_entry`)+ fd = _make_entry(lock_path)breakexcept FileExistsError:passdiff --git a/tests/conftest.py b/tests/conftest.pyindex d42f8bc..bfc6327 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -73,6 +73,9 @@ NOT_RIFE_SKIPS = {# os.kill(pid, 0) is a Ctrl+C to the console only on Windows, so only a Windows console holds what the case# measures; the lane's Linux host has none (its POSIX twin, the signal-0 case, runs there)."tests/spec/test_run_dir_lock.py::test_a_lock_holders_pid_is_judged_on_windows_without_a_ctrl_c_to_its_console",+ # Only Windows makes the lock entry on a CreateFileW handle handed to a descriptor; on POSIX os.open gives the+ # descriptor itself, so the lane's Linux host has no handle to close (its cross-platform twin, the descriptor case, runs).+ "tests/spec/test_run_dir_lock.py::test_a_lock_entry_handle_that_cannot_become_a_descriptor_is_closed_on_windows",}diff --git a/tests/spec/test_run_dir_lock.py b/tests/spec/test_run_dir_lock.pyindex b9bd4c0..30891fd 100644--- a/tests/spec/test_run_dir_lock.py+++ b/tests/spec/test_run_dir_lock.py@@ -30,6 +30,8 @@8. 락 주인이 살았는지는 그 프로세스에 아무것도 보내지 않고 본다 — POSIX 는 이 계약 전과 같은 신호 0 이고, Windows 는콘솔에 Ctrl+C 를 보내지 않는다(거기서 os.kill(pid, 0) 은 CTRL_C_EVENT 다). 살아 있는 프로세스와 열 수 없는 남의프로세스는 살아 있고, 끝난 프로세스는 아니다+ 9. 락 항목을 만든 fd 는 os.open 이 주던 fd 와 같은 성질이다 — 자식에게 상속되지 않고, 쓰기만 되고, 쓴 바이트가 그대로+ 놓이고, 열린 동안 그 이름을 지울 수 있는지도 같다. Windows 에서 만든 핸들을 fd 로 넘기지 못하면 그 핸들은 닫힌다3–8 은 실제 프로세스로 잰다 — 락은 프로세스 사이의 계약이고, 종료 처리는 프로세스가 끝날 때만 돈다. 3·6·7 은docs/run-contract.md §7 의 세 경계 밖에서다: C fork 자식이 끝나거나 exec 할 때까지의 커널 락, 시그널 처리기에서 fork 한 뒤 끊긴@@ -44,6 +46,7 @@ import jsonimport osimport queueimport signal+import statimport subprocessimport sysimport threading@@ -765,6 +768,64 @@ def test_a_writer_refuses_a_lock_name_that_is_not_a_lock_file_and_never_follows_assert _tree(tmp_path) == before, "락 이름 자리를 따라가 무엇을 지우거나 만들었다"+def _descriptor(fd: int, path: Path) -> dict[str, object]:+ """`path` 에 열린 쓰기 fd 의 성질 — 상속되는지, 읽으면 어떻게 끝나는지, 쓴 바이트가 그대로 놓이는지, 열린 동안 그 이름을+ 지울 수 있는지. fd 는 닫는다."""+ got: dict[str, object] = {"inheritable": os.get_inheritable(fd)}+ try:+ got["read"] = os.read(fd, 1)+ except OSError as exc:+ got["read"] = errno.errorcode.get(exc.errno, exc.errno)+ os.write(fd, b"a\nb\r\n")+ got["bytes"] = path.read_bytes()+ try:+ os.unlink(path)+ got["unlink-while-open"] = "removed"+ except PermissionError as exc:+ got["unlink-while-open"] = getattr(exc, "winerror", None) or exc.errno+ finally:+ os.close(fd)+ return got+++def test_the_lock_entry_is_made_on_a_descriptor_like_the_one_os_open_gives(tmp_path) -> None:+ """락 항목을 만드는 fd(Windows 는 이름 자체를 여는 CreateFileW 의 핸들을 넘긴 fd)는 os.open(O_CREAT|O_EXCL|O_WRONLY) 이+ 주던 fd 와 같은 성질이고, 이름에 새로 만든 그 일반 파일이다."""+ made_path, plain_path = tmp_path / "made", tmp_path / "plain"+ made = runio._make_entry(made_path)+ entry, seen = os.fstat(made), os.lstat(made_path)+ assert stat.S_ISREG(seen.st_mode) and (entry.st_dev, entry.st_ino) == (seen.st_dev, seen.st_ino)+ got = _descriptor(made, made_path)+ plain = _descriptor(os.open(plain_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0)), plain_path)+ assert got == plain, f"made {got} / os.open {plain}"+ assert got["inheritable"] is False and got["bytes"] == b"a\nb\r\n", got++[email protected](sys.platform != "win32", reason="Windows 의 CreateFileW 핸들 — POSIX 는 os.open 이 바로 fd 다")+def test_a_lock_entry_handle_that_cannot_become_a_descriptor_is_closed_on_windows(tmp_path, monkeypatch) -> None:+ """Windows 에서 락 항목의 핸들을 fd 로 넘기지 못하면(fd 표가 찼다) 그 오류로 끝나고 핸들은 닫힌다 — 열린 핸들은 그 이름을+ 지우지 못하게 막는데(공유 삭제 없음), 실패 뒤에는 지워지고 다시 만들어진다. 만든 빈 항목은 os.fstat 이 실패할 때처럼+ 남는다(주인을 확인할 수 없는 락)."""+ lock = tmp_path / runio.LOCK_FILENAME+ held = runio._make_entry(lock)+ with pytest.raises(PermissionError): # 열린 핸들은 지우기를 막는다 — 아래의 지우기가 닫힘을 잰다+ os.unlink(lock)+ os.close(held)+ os.unlink(lock)++ def full(handle: int, flags: int) -> int:+ raise OSError(errno.EMFILE, os.strerror(errno.EMFILE))++ monkeypatch.setattr(runio.msvcrt, "open_osfhandle", full)+ with pytest.raises(OSError) as failed:+ runio._make_entry(lock)+ monkeypatch.undo()+ assert failed.value.errno == errno.EMFILE+ assert lock.read_bytes() == b""+ os.unlink(lock) # 핸들이 남았으면 PermissionError(WinError 32)+ os.close(runio._make_entry(lock))++def test_an_old_lock_file_whose_holder_cannot_be_verified_is_reclaimed(tmp_path) -> None:run = tmp_path / "run"run.mkdir()