Skip to content

Use clear errors for invalid annotation writer inputs - #799

Merged
tompollard merged 3 commits into
mainfrom
annotation-writer-errors
Nov 30, 2026
Merged

tompollard merged 3 commits into
mainfrom
annotation-writer-errors

Conversation

@tompollard

@tompollard tompollard commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Closes #797.

Summary

write_annotations and Annotation.write passed some validation failures through from the shared annotation writer as tuple-valued exceptions. They now report plain messages. Both functions use the same validation (Annotation.write calls write_annotations), and the legacy wrann function and method get the same messages.

  • A non-empty annotation without a label field raises ValueError: A non-empty annotation needs at least one label field: label_store, symbol, or description, instead of a bare Exception with a tuple message. ValueError subclasses Exception, so existing except Exception handlers still work.
  • A field of the wrong type raises TypeError naming what it should be, such as The sample field must be a one-dimensional NumPy array, instead of a tuple of type objects.
  • A missing record_name or extension raises ValueError instead of a bare Exception.

While checking this, I found that the shape and type check for the numeric array fields (sample, label_store, subtype, chan, num) never ran: it compared the tuple of allowed types with np.ndarray, which is always false. So a two-dimensional sample failed inside np.concatenate, and a string array failed with '<' not supported between instances of 'numpy.str_' and 'int'. The check now runs and rejects arrays that are not one-dimensional or not numeric. It still accepts whole-number floats and object arrays of numbers, which the writer converts (the existing tests for those pass unchanged).

The whole-number check that sample already had now covers all five numeric fields. Before, fractional, NaN or infinite values in label_store, subtype, chan and num were silently truncated when written (for example, chan=1.5 was read back as 1, and NaN as 0), and object arrays of text failed with a raw comparison error. These now raise ValueError: The '<field>' field must only contain whole numbers.

Sample numbers must also be below 253. Larger values were converted to int64 unchecked: an unsigned 2**63 wrapped around and was read back as 0, and values such as 1e20 made the SKIP loop run for billions of iterations. 253 is where float64 stops representing every integer, and it bounds a file's SKIP elements at about 25 MB. Sample differences are now computed on signed integers, so decreasing unsigned samples are rejected, and full-size SKIP elements are built by repetition (the bytes are unchanged).

Tests

New tests run each case through both write_annotations and Annotation.write, and check the exact message and that no file is written: a missing label field, sample as a list, a 2D array and a string array, and wrong types for chan, symbol and fs. Further tests cover fractional, NaN, infinite and non-numeric object values in each numeric field, and check that whole-number float and object values are still written for each field. Others cover samples at or above 2**53, decreasing unsigned samples, and a round trip of gaps on each side of the SKIP boundaries.

Checks

  • Offline suite: 1,311 passed, 4 skipped
  • Ruff check and format: passed
  • Sphinx HTML build with warnings as errors: passed

@tompollard 🟥 red 🦥 sloth · aspen

A non-empty annotation without a label field now raises ValueError
instead of a bare Exception, and type errors name the field and what it
should be as a plain message, instead of a tuple of types.

The check of numeric array fields never ran, because it compared the
tuple of allowed types with np.ndarray. It now rejects arrays that are
not one-dimensional or not numeric, which previously failed inside
NumPy. Whole-number floats and object arrays of numbers are still
accepted.

Closes #797
@tompollard

Copy link
Copy Markdown
Member Author

I found one validation gap I think we should fix before merging. The new numeric-array check accepts any floating array, but the writer later casts values to bytes. I reproduced chan=np.array([1.5]) being written and read back as 1, and chan=np.array([np.nan]) being read back as 0 (with a NumPy warning). The same truncation occurs for subtype. An object array containing a string also passes the dtype check and then raises a raw comparison error instead of a field-specific message.

Could we check that values in sample, label_store, subtype, chan, and num are finite and whole before encoding, including elements of object arrays? That would preserve support for whole-number floats and numeric object arrays. Tests for fractional values, NaN, and nonnumeric object values would cover the gap.

The affected tests pass locally (89 passed, 3 network skips). Style and docs CI are green; the remaining jobs were still running when I checked.

The whole-number check applied only to sample. Fractional, NaN or
infinite values in label_store, subtype, chan and num were truncated when
written (chan=1.5 was read back as 1, and NaN as 0), and an object array
of text failed with a raw comparison error. The check now covers all five
fields, still accepting whole-number floats and numeric object arrays.
@tompollard

Copy link
Copy Markdown
Member Author

Thanks, good catch. Fixed in cb40e46. The whole-number check that sample already had now runs for all five numeric fields (sample, label_store, subtype, chan, num), in the shared array check, before anything is encoded:

  • Fractional, NaN and infinite values raise ValueError: The '<field>' field must only contain whole numbers instead of being truncated. chan=np.array([1.5]) and chan=np.array([np.nan]) are now rejected, as is subtype=[2.5]. label_store=[1.5] previously failed with a raw KeyError, and now gets the same message.
  • Object arrays are checked element by element. Fraction(3, 2), "a" and "1" are all rejected with the same message, rather than a raw comparison error.
  • Whole-number floats and numeric object arrays are still accepted for every field.

New tests cover each field with fractional, NaN, infinite and non-numeric object values, through both write_annotations and Annotation.write. They also check that no file is written and no NumPy warning is raised. A round-trip test checks that whole-number float and object values are still written for each field.

Offline suite: 1,301 passed, 4 skipped. Ruff and the strict docs build pass.

@tompollard

Copy link
Copy Markdown
Member Author

The validation gap I flagged is fixed in cb40e46. I reran the examples: fractional and NaN chan values, fractional subtype values, and nonnumeric object arrays now raise field-specific errors before a file is written. The 159 affected offline tests and Ruff pass locally. I’m happy with #799 once the remaining CI jobs pass.

I also found a separate, preexisting sample-range bug while checking boundaries: a uint64 sample of 2**63 writes and reads back as 0, and a sample of 1e20 can stall the writer. Both reproduce on main, so I’d track that separately rather than hold this PR.

The writer converted samples to int64 without checking their range. An
unsigned 2**63 wrapped around and was read back as 0, and values such as
1e20 overflowed and made the SKIP loop run for billions of iterations.

Sample numbers must now be below 2**53, where float64 still represents
every integer and the SKIP elements for a whole file stay under about
25 MB. Differences are computed on signed integers, so decreasing
unsigned samples are rejected, and full-size SKIP elements are built by
repetition instead of one at a time (the bytes are unchanged).
@tompollard

Copy link
Copy Markdown
Member Author

Thanks for checking the boundaries. I fixed the sample-range bug here as well, in d78b972:

  • Sample numbers must now be below 253, and larger values raise ValueError: The 'sample' field must only contain values below 2**53 before anything is written. 253 is where float64 stops representing every integer, and it bounds the SKIP elements for a whole file at about 25 MB, since each SKIP covers at most 231 - 1 samples. Your uint64 263 and 1e20 cases are rejected, as are 2.0**53 and an object array holding 2**70. Before, values just below 2**63 would also have stalled.
  • Differences are now computed on signed integers, so decreasing unsigned samples such as uint64 [5, 3] are rejected. Before, np.diff wrapped around and the ordering check passed.
  • Full-size SKIP elements are now built by repetition instead of one loop iteration each. I compared the bytes with the old loop on both sides of each SKIP boundary (1023/1024, 2**31 - 1 and its multiples) and they are identical. The largest allowed sample now writes in about 2 seconds.
  • Object arrays are checked for whole numbers with Python integers, so a huge integer gets the range message rather than a misleading "whole numbers" one.

New tests cover the four over-limit cases through both writers, decreasing unsigned samples, and a round trip of gaps on each side of the SKIP boundaries up to 2**40. Offline suite: 1,311 passed, 4 skipped. Ruff and the strict docs build pass.

@tompollard
tompollard merged commit 63796af into main Nov 30, 2026
19 checks passed
@tompollard
tompollard deleted the annotation-writer-errors branch November 30, 2026 18: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.

Use clear errors for invalid annotation writer inputs

1 participant