Skip to content

Validate signal values before creating write outputs - #881

Merged
tompollard merged 2 commits into
mainfrom
fix/preflight-signal-writes
Dec 3, 2026
Merged

tompollard merged 2 commits into
mainfrom
fix/preflight-signal-writes

Conversation

@tompollard

@tompollard tompollard commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Fixes #880.

write_record could write a header before the .dat encoder noticed an out-of-range sample, leaving a partial record and raising IndexError. This adds a shared preflight check in _WriteModel.write, after calibration and defaults are resolved and before any file is created. It covers write_record, SignalRead.write, and write_signals, and removes the temporary after_features callback.

Physical values are checked against the rounded, calibrated format range and reserved missing marker. Digital values are checked against the target format's range. An in-range reserved marker remains valid in a digital Record, where it represents a missing sample; masked modern reads have already encoded their masks before this check. The physical range check uses channel extrema to avoid another full signal copy.

The new tests cover all three writers, physical and digital values, uniform and expanded layouts, local stems and archives, marker collisions, boundary rounding, and empty destinations after failure. A changelog entry calls out the new ValueError and no-partial-file behavior.

Checks: 2,225 offline tests passed (48 skipped), Ruff passed, and the warning-as-error docs build passed. Existing byte-comparison tests passed. The physical preflight runs before ADC conversion when calibration is known, so invalid casts do not emit a NumPy warning first. On a local 20-run write benchmark of the full 100skew record (macOS arm64, Python 3.11.13, NumPy 2.4.6, time measured with tracemalloc), median digital writes were 15.3 → 14.3 ms and physical writes 20.3 → 21.2 ms; peak traced memory was unchanged.

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

This fixes #880, and the shared check in the model is a better design than the callback. I'd fix one small regression before merging. The offline suite (2,211 passed, 48 skipped) and Ruff pass locally.

What I checked

  • write_record no longer leaves a partial record. An out-of-range digital sample (d_signal[0, 0] = 5000 in format 212) now raises ValueError: digital channel 0 exceeds format 212's allowed range -2048 to 2047, and the destination stays empty. On main, it raised IndexError and left wd.hea. Out-of-range and marker-valued physical values are rejected before any file appears in all three writers.
  • The extremes-only physical check is correct for every writable format. Range: positive gain and round-half-even preserve order, so the converted minimum and maximum bound every sample. Marker: checking only converted_min == marker relies on the marker being the bottom of the range. That's true for all eight writable formats today (80, 212, 16, 24, 32, 508, 516, 524 each have marker == lower). Because the code depends on it silently, a test that asserts _digi_nan(fmt) == SAMPLE_VALUE_RANGE[fmt][0] for every entry in WRITABLE_FMTS would catch a future format that breaks it. A full check as a fallback when it doesn't hold would also work.
  • Inputs are unchanged. My 1,464-write SignalRead.write check still shows no changed arrays or retained fields, with the same 232 expected errors.
  • Performance stays within the 10% target. On my machine (100skew, 15 runs, write only, against #879's head):
    • write_record: 10.44 → 10.80 ms digital, 16.71 → 17.85 ms physical (+7%).
    • SignalRead.write: 8.12 → 8.51 ms digital; physical improves, 17.18 → 14.49 ms.
    • write_signals physical: 33.09 → 30.39 ms.
    • Peak memory is unchanged.

Fix before merging: a RuntimeWarning before the error

The physical check now runs after ADC conversion, where #879 ran it before when calibration was known. So an infinite or very large physical value is cast to an integer first, and NumPy warns before the ValueError:

read = wfdb.read_signals("sample-data/100", kind="physical", layout="uniform", stop=5)
read.signals.values[0, 0] = np.inf     # or 1e300
read.write(path)
# 4bf6a8f: ValueError only
# here:    RuntimeWarning: invalid value encountered in cast, then ValueError

write_signals(..., adc_gain=[200.0], baseline=[0]) with 1e300 gives the same result. No file is written, but users see a confusing NumPy warning before the real error, and anyone running with -W error gets the warning raised instead of the ValueError. I'd run the physical check before adc whenever fmt, adc_gain and baseline are already known, and after set_d_features only when calibration is being calculated. Please add a test that the failing write raises no warnings (warnings.simplefilter("error") inside the pytest.raises block).

@tompollard

Copy link
Copy Markdown
Member Author

Thanks — fixed in 89bc370. When format, gain, and baseline are known, the model now checks physical values before ADC conversion. For flattened records it does this after selecting the target calibration but before converting the values. Calibration inferred during feature calculation is still checked afterwards.

I added warning-as-error tests for infinity and 1e300 through all three modern writers, plus a test that every writable format's missing marker is its lower bound. The byte-parity tests also caught a changed error order for an unsupported-format fixture; I preserved its previous error. The full offline suite passes (2,225 passed, 48 skipped), as do Ruff and the docs build. CI is rerunning on the new commit.

@tompollard
tompollard merged commit b76761d into main Dec 3, 2026
19 checks passed
@tompollard
tompollard deleted the fix/preflight-signal-writes branch December 3, 2026 06:27
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.

Validate signal values before write_record creates files

1 participant