From 259147c43d89e89a2c9bb0960976fcbf3dce5e76 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 19:20:58 -0500 Subject: [PATCH 1/3] Write multi-segment records completely or not at all MultiRecord.wrsamp already checked the segments' lengths before writing, but wrote the main header and earlier segments before finding that a later segment could not be written. Write the files into a temporary directory in write_dir and move them into place once every segment has been written. Before writing, check that each segment has the signal to write, and samps_per_frame for expanded signals, so that these give a ValueError naming the segment rather than a TypeError. Pass write_dir when opening an archive, so that a relative wfdb_archive path is relative to it, as in Record.wrsamp. Fixes #557. --- changelog.d/multirecord-write-checks.rst | 10 +++ src/wfdb/io/record.py | 96 ++++++++++++++++++++---- tests/test_multi_record.py | 68 +++++++++++++++++ 3 files changed, 161 insertions(+), 13 deletions(-) create mode 100644 changelog.d/multirecord-write-checks.rst diff --git a/changelog.d/multirecord-write-checks.rst b/changelog.d/multirecord-write-checks.rst new file mode 100644 index 00000000..6a2bcb93 --- /dev/null +++ b/changelog.d/multirecord-write-checks.rst @@ -0,0 +1,10 @@ +**Write multi-segment records completely or not at all** + ``MultiRecord.wrsamp`` wrote the main header and the earlier segments + before finding that a later segment could not be written, which left a + partly written record. It now writes the files into a temporary folder in + ``write_dir``, and moves them into place only once every segment has been + written. A segment without the signal to write, or without + ``samps_per_frame`` when writing expanded signals, now raises a + ``ValueError`` that names the segment, instead of a ``TypeError``. A + relative ``wfdb_archive`` path is now relative to ``write_dir``, as it is + for ``Record.wrsamp``. diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index dd8e1284..200a120d 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -4,6 +4,7 @@ import os import posixpath import re +import tempfile import numpy as np import pandas as pd @@ -1202,22 +1203,91 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): N/A """ - # Validate segment cohesion before writing anything. + # Validate the segments before writing anything. self._check_segment_cohesion() + self._check_segment_signals(expanded) - with archive_for_writing(wfdb_archive) as archive: - # Perform field validity and cohesion checks, and write the - # header file. - self.wrheader(write_dir=write_dir, wfdb_archive=archive) - # Perform record validity and cohesion checks, and write the - # associated segments. Empty segments ('~') have no files. - for seg in self.segments: - if seg is not None: - seg.wrsamp( - expanded=expanded, - write_dir=write_dir, - wfdb_archive=archive, + if wfdb_archive is not None: + # An archive opened from a path is discarded if writing fails + with archive_for_writing(wfdb_archive, write_dir) as archive: + self._write_segments(expanded, write_dir, archive) + return + + # Write the files into a temporary directory first, and move them into + # write_dir only once every segment has been written, so that a segment + # that cannot be written leaves no partly written record behind. + # (in write_dir itself, so that the files can be moved, not copied) + with tempfile.TemporaryDirectory( + dir=write_dir or os.curdir, prefix=".wfdb-" + ) as staging: + self._write_segments(expanded, staging, None) + for name in os.listdir(staging): + os.replace(os.path.join(staging, name), os.path.join(write_dir, name)) + + def _write_segments(self, expanded, write_dir, wfdb_archive): + """Write the multi-segment header, and the files of each segment. + + Parameters + ---------- + expanded : bool + Whether to write each segment's expanded signal. + write_dir : str + The directory in which to write the files. + wfdb_archive : WFDBArchive or None + The archive to write the files into, if any. + + Returns + ------- + N/A + + """ + # Perform field validity and cohesion checks, and write the header file. + self.wrheader(write_dir=write_dir, wfdb_archive=wfdb_archive) + # Perform record validity and cohesion checks, and write the associated + # segments. Empty segments ('~') have no files. + for seg in self.segments: + if seg is not None: + seg.wrsamp( + expanded=expanded, write_dir=write_dir, wfdb_archive=wfdb_archive + ) + + def _check_segment_signals(self, expanded): + """Check that each segment has the signal that is to be written. + + Parameters + ---------- + expanded : bool + Whether each segment's expanded signal is to be written. + + Returns + ------- + N/A + + """ + for seg_num, segment in enumerate(self.segments): + # Empty segments, and the layout header of a variable layout + # record, have no signal files + if segment is None or ( + segment.file_name is not None + and all(f == "~" for f in segment.file_name) + ): + continue + name = f"Segment {seg_num} ({segment.record_name})" + if expanded: + if segment.e_d_signal is None and segment.e_p_signal is None: + raise ValueError( + f"{name} has no expanded signal (e_d_signal or e_p_signal) " + "to write with expanded=True" ) + if segment.samps_per_frame is None: + raise ValueError( + f"{name} has no samps_per_frame, which is needed to " + "write its expanded signal" + ) + elif segment.d_signal is None and segment.p_signal is None: + raise ValueError( + f"{name} has no signal (d_signal or p_signal) to write" + ) def _check_segment_cohesion(self): """Check the cohesion of the segments field with the other fields. diff --git a/tests/test_multi_record.py b/tests/test_multi_record.py index 0c8615c3..fa772dbc 100644 --- a/tests/test_multi_record.py +++ b/tests/test_multi_record.py @@ -178,3 +178,71 @@ def test_unspecified_samps_per_frame_is_accepted_when_expanded(self, tmp_path): smooth_frames=False, ) assert record_write.segments[0].samps_per_frame == [1] + + @pytest.mark.parametrize("expanded", [False, True]) + def test_invalid_later_segment_writes_no_files(self, tmp_path, expanded): + """A segment that fails to be written leaves no partial record (#557).""" + record = wfdb.rdrecord( + self.record_path, m2s=False, physical=False, smooth_frames=not expanded + ) + segment = record.segments[1] + if expanded: + segment.e_d_signal[0] = segment.e_d_signal[0][:-3] + else: + segment.fmt = ["999"] * segment.n_sig + + with pytest.raises(ValueError): + record.wrsamp(write_dir=str(tmp_path), expanded=expanded) + + assert list(tmp_path.iterdir()) == [] + + def test_segment_without_samps_per_frame_when_expanded(self, tmp_path): + record = wfdb.rdrecord( + self.record_path, m2s=False, physical=False, smooth_frames=False + ) + record.segments[1].samps_per_frame = None + + with pytest.raises(ValueError, match=r"Segment 1 \(041s02\) has no samps"): + record.wrsamp(write_dir=str(tmp_path), expanded=True) + + assert list(tmp_path.iterdir()) == [] + + @pytest.mark.parametrize("expanded", [False, True]) + def test_segment_without_a_signal(self, tmp_path, expanded): + record = wfdb.rdrecord( + self.record_path, m2s=False, physical=False, smooth_frames=not expanded + ) + segment = record.segments[1] + segment.d_signal = segment.p_signal = None + segment.e_d_signal = segment.e_p_signal = None + + with pytest.raises(ValueError, match=r"Segment 1 \(041s02\) has no"): + record.wrsamp(write_dir=str(tmp_path), expanded=expanded) + + assert list(tmp_path.iterdir()) == [] + + def test_write_to_the_current_directory(self, tmp_path, monkeypatch): + """The default write_dir is the current directory, with no files left over.""" + record = wfdb.rdrecord(self.record_path, m2s=False, physical=False) + monkeypatch.chdir(tmp_path) + + record.wrsamp() + + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "041s.hea", + "041s01.dat", + "041s01.hea", + "041s02.dat", + "041s02.hea", + ] + + def test_archive_path_is_relative_to_write_dir(self, tmp_path, monkeypatch): + record = wfdb.rdrecord(self.record_path, m2s=False, physical=False) + monkeypatch.chdir(tmp_path) + (tmp_path / "out").mkdir() + + record.wrsamp(write_dir="out", wfdb_archive="041s.wfdb") + + assert [p.name for p in (tmp_path / "out").iterdir()] == ["041s.wfdb"] + assert not (tmp_path / "041s.wfdb").exists() + assert wfdb.rdrecord("out/041s.wfdb").sig_len == record.sig_len From c34985dc3b5fcd95427625f26f190df0a387973d Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 19:25:51 -0500 Subject: [PATCH 2/3] Keep permissions of replaced files, and undo a failed move Moving the written files into place gave a replaced file the new file's permissions, and a failure partway through left the files moved so far. Give each new file the permissions of the file it replaces, move replaced files aside rather than deleting them, and if a move fails, remove the files already moved and restore the replaced ones before raising the error. --- changelog.d/multirecord-write-checks.rst | 4 +- src/wfdb/io/record.py | 48 +++++++++++++++++++++- tests/test_multi_record.py | 52 ++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 3 deletions(-) diff --git a/changelog.d/multirecord-write-checks.rst b/changelog.d/multirecord-write-checks.rst index 6a2bcb93..c714af92 100644 --- a/changelog.d/multirecord-write-checks.rst +++ b/changelog.d/multirecord-write-checks.rst @@ -3,7 +3,9 @@ before finding that a later segment could not be written, which left a partly written record. It now writes the files into a temporary folder in ``write_dir``, and moves them into place only once every segment has been - written. A segment without the signal to write, or without + written. Files that are replaced keep their permissions, and if a move + fails, the files already moved are removed and the replaced files are + restored. A segment without the signal to write, or without ``samps_per_frame`` when writing expanded signals, now raises a ``ValueError`` that names the segment, instead of a ``TypeError``. A relative ``wfdb_archive`` path is now relative to ``write_dir``, as it is diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 200a120d..142ff035 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -4,6 +4,7 @@ import os import posixpath import re +import shutil import tempfile import numpy as np @@ -1054,6 +1055,50 @@ def to_dataframe(self) -> pd.DataFrame: return pd.DataFrame(data=data, index=index, columns=self.sig_name) +def _move_files_into_place(source_dir, target_dir): + """Move every file in a directory into another directory, all or none. + + A file that replaces an existing file gets that file's permissions. If a + move fails, the files that were already moved are removed and the files + they replaced are restored, before the error is raised again, so that + `target_dir` is left as it was. + + Parameters + ---------- + source_dir : str + The directory of the files to move. The files that are replaced are + kept in a folder in it until all the files have been moved. + target_dir : str + The directory to move the files into, on the same file system. + + Returns + ------- + N/A + + """ + names = sorted(os.listdir(source_dir)) + replaced_dir = os.path.join(source_dir, ".replaced") + os.mkdir(replaced_dir) + moved = [] + replaced = [] + try: + for name in names: + new_file = os.path.join(source_dir, name) + target = os.path.join(target_dir, name) + if os.path.lexists(target): + shutil.copymode(target, new_file) + os.replace(target, os.path.join(replaced_dir, name)) + replaced.append(name) + os.replace(new_file, target) + moved.append(name) + except BaseException: + for name in moved: + os.remove(os.path.join(target_dir, name)) + for name in replaced: + os.replace(os.path.join(replaced_dir, name), os.path.join(target_dir, name)) + raise + + class MultiRecord(BaseRecord, _header.MultiHeaderMixin): """The class representing multi-segment WFDB records. @@ -1221,8 +1266,7 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): dir=write_dir or os.curdir, prefix=".wfdb-" ) as staging: self._write_segments(expanded, staging, None) - for name in os.listdir(staging): - os.replace(os.path.join(staging, name), os.path.join(write_dir, name)) + _move_files_into_place(staging, write_dir or os.curdir) def _write_segments(self, expanded, write_dir, wfdb_archive): """Write the multi-segment header, and the files of each segment. diff --git a/tests/test_multi_record.py b/tests/test_multi_record.py index fa772dbc..2e4e2c8d 100644 --- a/tests/test_multi_record.py +++ b/tests/test_multi_record.py @@ -1,3 +1,6 @@ +import os +import stat + import numpy as np import pytest @@ -246,3 +249,52 @@ def test_archive_path_is_relative_to_write_dir(self, tmp_path, monkeypatch): assert [p.name for p in (tmp_path / "out").iterdir()] == ["041s.wfdb"] assert not (tmp_path / "041s.wfdb").exists() assert wfdb.rdrecord("out/041s.wfdb").sig_len == record.sig_len + + @pytest.mark.skipif(os.name == "nt", reason="POSIX file permissions") + def test_overwriting_keeps_file_permissions(self, tmp_path): + record = wfdb.rdrecord(self.record_path, m2s=False, physical=False) + record.wrsamp(write_dir=str(tmp_path)) + (tmp_path / "041s01.dat").chmod(0o600) + + record.wrsamp(write_dir=str(tmp_path)) + + mode = stat.S_IMODE((tmp_path / "041s01.dat").stat().st_mode) + assert mode == 0o600 + + @staticmethod + def fail_second_move(monkeypatch, target): + """Make the second move of a new file into `target` fail.""" + real_replace = os.replace + moves = [] + + def replace(src, dst): + into_target = os.path.dirname(os.path.abspath(dst)) == str(target) + if into_target and ".replaced" not in str(src): + moves.append(dst) + if len(moves) == 2: + raise OSError("disk full") + real_replace(src, dst) + + monkeypatch.setattr(os, "replace", replace) + + def test_failed_move_leaves_no_files(self, tmp_path, monkeypatch): + record = wfdb.rdrecord(self.record_path, m2s=False, physical=False) + self.fail_second_move(monkeypatch, tmp_path) + + with pytest.raises(OSError, match="disk full"): + record.wrsamp(write_dir=str(tmp_path)) + + assert list(tmp_path.iterdir()) == [] + + def test_failed_move_restores_the_record_it_replaces(self, tmp_path, monkeypatch): + record = wfdb.rdrecord(self.record_path, m2s=False, physical=False) + record.wrsamp(write_dir=str(tmp_path)) + before = {p.name: p.read_bytes() for p in tmp_path.iterdir()} + for segment in record.segments: + segment.d_signal = segment.d_signal // 2 + self.fail_second_move(monkeypatch, tmp_path) + + with pytest.raises(OSError, match="disk full"): + record.wrsamp(write_dir=str(tmp_path)) + + assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before From 1958a9259b9564835b56923e310aeb6d42a4be5e Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 19:29:18 -0500 Subject: [PATCH 3/3] Say what MultiRecord.wrsamp does and does not guarantee on errors --- changelog.d/multirecord-write-checks.rst | 6 ++++-- src/wfdb/io/record.py | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/changelog.d/multirecord-write-checks.rst b/changelog.d/multirecord-write-checks.rst index c714af92..93ccfe6d 100644 --- a/changelog.d/multirecord-write-checks.rst +++ b/changelog.d/multirecord-write-checks.rst @@ -1,11 +1,13 @@ -**Write multi-segment records completely or not at all** +**Leave no partly written multi-segment record after an error** ``MultiRecord.wrsamp`` wrote the main header and the earlier segments before finding that a later segment could not be written, which left a partly written record. It now writes the files into a temporary folder in ``write_dir``, and moves them into place only once every segment has been written. Files that are replaced keep their permissions, and if a move fails, the files already moved are removed and the replaced files are - restored. A segment without the signal to write, or without + restored. The files are moved one at a time, so a program reading them + meanwhile, or a crash while they are moved, can still see a mix of files. + A segment without the signal to write, or without ``samps_per_frame`` when writing expanded signals, now raises a ``ValueError`` that names the segment, instead of a ``TypeError``. A relative ``wfdb_archive`` path is now relative to ``write_dir``, as it is diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 142ff035..851e1ed1 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -1228,6 +1228,13 @@ def __init__( def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): """Write a multi-segment header and the headers and dat files of its segments. + The files are written into a temporary folder in `write_dir`, and + moved into `write_dir` once every segment has been written. If an + error occurs, no files are left in `write_dir`, and any files that + were being replaced are restored. The files are moved one at a time, + so a program reading them meanwhile, or a crash while they are moved, + can still see a mix of old and new files. + Parameters ---------- expanded : bool, optional