Skip to content

Path.copy() silently truncates the source when a reused destination path becomes a hard link to it #162689

Backlog

Description

@limadog9

Bug report

On Linux, Path.copy() can return successfully after emptying its source file. This happens when an earlier copy used the same destination Path object and the destination was subsequently replaced with a hard link to the source.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as tmp:
    src = Path(tmp) / "source.txt"
    dst = Path(tmp) / "backup.txt"
    src.write_bytes(b"original data")
    dst.write_bytes(b"old backup")

    src.copy(dst)
    dst.unlink()
    dst.hardlink_to(src)

    assert src.samefile(dst)
    assert src.read_bytes() == b"original data"
    src.copy(dst)
    print(src.read_bytes(), dst.read_bytes())

Expected: The second copy() raises OSError and preserves b"original data". Replacing only that call with src.copy(Path(dst)) produces this behavior on the same files.

Actual: The second copy() returns normally and the output is b'' b''.

The first copy caches the destination’s file identity. After dst is replaced, src.samefile(dst) correctly returns True, but the same-file check inside copy() uses the old identity. It then opens dst in wb mode, truncating the shared inode before any bytes are copied. The reproducer is single-threaded and never accesses Path.info explicitly.

Reproduced on Linux with CPython 3.14.10, 3.15.2, 3.16.0a2, and main at 3b309372.

CPython versions tested on:

3.14, 3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    type-bug
    on Nov 26, 2026
  2. added
    stdlib
    on Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-pathlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions