Skip to content

Leave no partly written multi-segment record after an error - #673

Merged
tompollard merged 3 commits into
mainfrom
multirecord-segment-checks
Nov 24, 2026
Merged

tompollard merged 3 commits into
mainfrom
multirecord-segment-checks

Conversation

@tompollard

@tompollard tompollard commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Fixes #557.

The "good initial step" in the issue, calling _check_segment_cohesion before writing, is already on main (3880107, in 5.0.0). This covers the rest of what the issue asks for, and what the checks miss.

A later segment that fails no longer leaves a partial record. The cohesion check only covers lengths and fs. Anything that Record.wrsamp rejects in a later segment (an invalid format, an expanded signal of the wrong length, and so on) was found only after the main header and the earlier segments had been written:

Second segment of 041s main: files left after the error Now
expanded signal 3 samples short 041s.hea, 041s01.hea, 041s01.dat, 041s02.hea none
invalid format 041s.hea, 041s01.hea, 041s01.dat none

MultiRecord.wrsamp now writes into a temporary folder inside write_dir, and moves the files into place (with os.replace, on the same file system) only once every segment has been written. Writing to a .wfdb archive opened from a path was already all-or-nothing, since the archive is discarded on an error. Files that are replaced keep their permissions, and if one of the moves fails, the files already moved are removed and the replaced files are restored. A crash partway through the moves can't be undone.

Clear errors for missing signals. As the issue suggests, each segment is checked before writing for the signal to write (d_signal or p_signal, or e_d_signal or e_p_signal with expanded=True) and, for expanded signals, samps_per_frame. These gave TypeError: object of type 'NoneType' has no len() or iteration over a 0-d array, and now give a ValueError such as "Segment 1 (041s02) has no samps_per_frame, which is needed to write its expanded signal". Empty segments and the layout header of a variable layout record are skipped, as they have no signal files.

Archive paths relative to write_dir. MultiRecord.wrsamp(write_dir="out", wfdb_archive="041s.wfdb") wrote the archive to the current directory, because write_dir wasn't passed when opening it. It now goes in out/, as with Record.wrsamp.

Testing

  • New tests: a later segment that fails (non-expanded and expanded) writes no files; missing samps_per_frame and missing signals give the new errors; writing to the current directory leaves no temporary folder; a relative archive path is relative to write_dir; overwriting keeps file permissions; and a failed move leaves an empty folder empty and restores a record it was replacing. All but the current-directory test fail on main.
  • pytest: all offline and network tests pass. Ruff and the docs build pass.

@tompollard 🟥 red 🦥 sloth · aspen

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.

@tompollard tompollard left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 259147c. I found two issues in the staged-file commit step (src/wfdb/io/record.py, lines 1220-1225):

  1. Preserve existing file permissions when overwriting a record. os.replace gives the destination the staged file's permissions. With umask 022, I wrote a record, changed 041s01.dat to mode 0600, then wrote it again: this PR changed the file to 0644, while the base version kept it at 0600. That can expose data in a shared directory. Please preserve each existing file's mode on replacement.

  2. Handle a failure during the final moves. The files are replaced one by one without rollback. When I made the second os.replace raise OSError, the first moved file remained in the output directory (041s01.hea), leaving a partial record. Replacing an existing record can likewise leave old and new files mixed. Please handle this case, or narrow the all-or-nothing guarantee and document the limitation.

All 18 focused offline multi-record tests pass. CI has no failures so far, with several jobs still running. I would address these before merging.

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.
@tompollard

tompollard commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

Thanks, both fixed in c34985d, in a new helper, _move_files_into_place.

  1. Permissions: before a new file replaces an existing one, it gets the existing file's permissions (shutil.copymode). New files are created as before, so they get the usual permissions from the umask. A test writes a record, changes 041s01.dat to 0600, writes it again and checks that it's still 0600. It fails on the previous commit.

  2. A failed move: existing files are now moved aside, into a folder in the staging directory, rather than deleted. If any move fails, the files already moved are removed and the old files are put back, and then the error is raised. Two tests make the second move fail with OSError:

    • writing into an empty folder leaves it empty;
    • overwriting an existing record leaves its files byte for byte as they were, after a change to the signals that alters four of them.

    Both fail on the previous commit.

Two limits remain:

  • A crash or power loss partway through the moves can't be undone. The window is a handful of renames in one directory.
  • A replaced file is a new file with the old one's permissions, so other properties of the old file, such as its owner or hard links to it, aren't carried over. That's the usual trade-off for replacing files atomically, rather than writing over them in place.

All offline tests and ruff pass.

@tompollard tompollard left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed commit c34985d. Both findings from my earlier review are resolved: overwriting an existing record now preserves its file modes, and a simulated failure during the final moves restores the previous files. The 21 focused offline multi-record tests pass. I found no new blocker. Docs and style checks pass; the test matrix is still running.

One wording caveat: the rollback covers handled write errors. Sequential moves cannot provide a single atomic view to concurrent readers or recover from a process crash, so the all-or-nothing claim should be read in that narrower sense.

@tompollard tompollard changed the title Write multi-segment records completely or not at all Leave no partly written multi-segment record after an error Nov 24, 2026
@tompollard

Copy link
Copy Markdown
Member Author

Agreed, thanks. The guarantee is narrower than "all or nothing", so in 1958a92 I changed the wording to match:

  • PR title and changelog heading: now "Leave no partly written multi-segment record after an error".
  • Changelog entry and MultiRecord.wrsamp docstring: they now say what is covered (an error while writing or moving the files leaves no new files, and restores any files that were being replaced). They also say what isn't: the files are moved one at a time, so a program reading them meanwhile, or a crash during the moves, can still see a mix of old and new files.

No code changes in this commit. The docs build and ruff pass.

@tompollard
tompollard merged commit 3739fb8 into main Nov 24, 2026
18 checks passed
@tompollard
tompollard deleted the multirecord-segment-checks branch November 24, 2026 00:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add validation of segments when writing a MultiRecord

1 participant