Repository navigation
Read EEGLAB .set headers for the channel-count gate - #1564
Conversation
A .set had no header count, so a store short of an inherited channels.tsv was refused even when it held every channel the file declares (on003645: 75-channel EEG under a 404-row MEG sidecar). Read nbchan from classic MAT v5/v7 (bounded streaming parse, never the sample matrix) and v7.3 (h5py metadata), and return it only where it equals the rows biosigIO serves. Tested with real files through convert_one; mutations of each guard fail the suite.
The struct walk skipped past data before its both-seen check, so a compressed EEG inflated every sample. Return as soon as nbchan and data are read. Adds a hand-built MAT v5 writer to the tests and a regression test whose deflate stream is garbage after the first 64 KiB of samples. Tested: pytest TestEeglabDeclaredChannelCount.
Shrink the MAT stream chunk to 64 KiB and test a 51 MB matrix, with nbchan before and after data, against a 3.2 MB bound; the parser peaks under 0.4 MB. Tested: pytest never_loaded.
Add EEGLAB_MAX_HEADER_READ_BYTES (256 MiB) across one classic .set header read; past it the read gives up with the usual single warning. Tested: a zlib bomb declaring cap + 1 MiB of zeros before nbchan returns None in under a second; one just under the cap still counts.
Explain why a fractional nbchan (biosigIO truncates classic, rounds v7.3) and an nbchan below the matrix rows both return None. Tests pin the importer's two readings of 3.6 and add the v7.3 nbchan-below-rows case. Tested: pytest fractional/disagreeing.
Cover big-endian files (including small-element nbchan), a 1xN EEG struct array, nbchan after data, variables around EEG, and truncation at every 2% and each of the first 512 bytes of three real files, each read bounded by a 5 s alarm. Tested: pytest, 1716 subtests.
A store short of its channels.tsv no longer counts as channel_count_mismatch when its own index entry discloses channels_tsv_count_mismatch with in_store == in_file == the store's total. A store short of its header, or short of the sidecar with no valid disclosure, is still flagged. Tested: bun test zarr-fidelity-sweep (73 pass).
464cd42 to
92b487c
Compare
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR1564Version: 🤖 Updated on each push. |
The comment said 15 channels; its own arithmetic gives 16. Comment only, not tested.
|
Review record, round 1 fixes (Sonnet review of 92b487c, head now 00ce4ec). No critical or important findings. The sweep excuse Suggestions:
|
Summary
The Zarr converter's always-on channel-count gate now reads the channel count from EEGLAB
.setheaders, as it already does for EDF/BDF, BrainVision and FIF.Problem (on003645, on hallu). The dataset mixes MEG
.fifand EEG.setrecordings. Its subject-levelchannels.tsvlists 404 MEG channels, and the EEG recordings inherit it. Their.setfiles hold 75 channels.file_declared_channel_countreturned None for.set, sostore 75 < sidecar 404had no header to prove the store complete. All 108 EEG recordings were refused aschannel_count_mismatch. A.fifin the same situation is served with asidecar_overcountdisclosure; a.setnow gets the same treatment.Changes
file_declared_channel_count: new.setbranch (_eeglab_declared_channel_count)_is_matlab_v73does it, from the MAT header text.EEG/nbchan, or the flat root when that root has nbchan/srate/pnts/data. AnEEGgroup wins when both layouts exist.Dataset.shapegives the matrix's shape without reading any samples._mat5_eeglab_header). It walks element headers, skips uncompressed variables by seeking, and decompresses in 1 MB chunks that it throws away. It stops oncenbchananddatahave both been seen, and never readsdatapast its dimensions.scipy.io.loadmat(variable_names=...): I measured it, and it does not keep the read cheap. A real EEGLAB export is ONE variable,EEG, withdatainside it.loadmat(variable_names=["EEG"])on a 100 MB inline-data.setpeaked at 103 MB traced. The flat layout alone would be cheap. On the same files the new reader peaks at about 0.01 MB (uncompressed) and 5 MB (compressed).EEGstruct and flat variables. TheEEGfield wins, as in biosigIO's_normalize_eeglab_dict. For a struct array, the first element is used..fdt-backed: returnsnbchan.nbchanonly if it equals the matrix's row count. On disagreement it returns None, with one::warning::.::warning::, in the FIF branch's wording: unreadable, truncated or corrupt files, a missing nbchan or data, and a nonpositive, fractional or absurd (>100000) nbchan. With None, the gate falls back to channels.tsv alone, which is the old strict behavior.MemoryErroris re-raised.file_declared_channel_countandexpected_channel_count_for's description of the two ground truths still holds.in_filedescription inshared/zarr-index.schema.jsonnow names FIFnchanand EEGLABnbchan. Before, it listed only EDF/BDF and BrainVision. Text only, no structural change..memory/repeated-channel-labels-collapse-stores.md:.setis moved out of the "no cheap header" list, and the note records theloadmattrap.test_a_format_with_no_cheap_header_is_unknown_without_a_warningused.setas its example of a format with no header. It now uses KIT.con.Header count vs importer parity (biosigio 1.2.10,
importers/eeglab.py)Both
_loadand_load_v73treat the data matrix as authoritative.chanlocsonly names rows: a short chanlocs is padded and a long one is trimmed. Anbchanthat disagrees with the matrix is only a warning, and the matrix rows are served. For a.fdt, the file is reshaped to(nbchan, pnts*trials)and refused when its size disagrees. Sonbchanis a faithful count only where the matrix cannot disagree with it. I checked every case by importing the same real file with biosigIO and building a store:.fdt(wrapped/flat).fdt.fdtICA activations and reference (
nodatchans) channels are neither indatanor innbchan, so they cannot skew the count. Real files agree too:.set(OpenNeuro ds003645 sub-002 run-1, MATLAB-written, flat, compressed,.fdt) reads as 75 in 0.003 s, and biosigIO imports 75 columns.test_raw.set,test_raw_onefile.set,test_epochs.set,test_raw_h5.set) all match the importer.Tests (real files written with scipy/h5py, no mocks)
TestEeglabDeclaredChannelCount(unit tests, each count cross-checked against biosigIO's import of the same file):.fdt.fdtand squareEEGwinning over flat variables.set,tracemallocshowsloadmat(variable_names=["EEG"])peaking above 90% of the data size and the header read below a third of it. The bound is shown to tell the two reads apart.truncated/ChannelCountMismatch, with every sidecar value (None, 3, 5, 404).TestConvertOneEeglabSidecarOvercount(throughconvert_one):.setpublishes. It is synced, the entry carrieschannels_tsv_count_mismatch == {channels_tsv: N, in_file: 3, in_store: 3}, and the index is schema-valid. Covered for classic inline, classic.fdt, classic flat, v7.3 inline and v7.3.fdt.channel_count_mismatchagainst the sidecar alone, and nothing is synced..setis refused before any store exists.TestDeclaredFdtConvertOne.test_the_header_gate_reads_the_staged_set: the ADR 0073 declared-.fdtpath discloses an over-declaring sidecar..setdispatch, trusting nbchan over the rows, dropping the v7.3 transpose rule, letting flat win overEEG, accepting nonpositive nbchan, distrusting.fdt, and loadingEEGwhole. Each one fails the suite.Results
test_generate_zarr.py test_zarr_queue.py test_purge_non_raw_stores.py test_find_collapsed_channel_stores.py test_patch_power_line_frequency.pywith biosigio 1.2.10: 965 passed, 5 skipped (Linux-only RLIMIT and /proc tests), 0 failed.test_hallu_zarr_config.py: 51 passed locally. The other 74 need bash 4+ (this macOS has bash 3.2) and are left to Linux CI. No hallu file is touched.bun test zarr mcp: 879 pass at the root and 679 in backend.After the next release
zarr_queue.py requeue --status done --dataset on003645 --execute, or run it with--dataset..setrecordings under an over-declaring or inherited channels.tsv were likely refused the same way. Two ways to find them:channel_count_mismatchon a.setpath;scripts/zarr/find_collapsed_channel_stores.py, which is read-only. Its default mode checks published stores and counts a store short of channels.tsv without an overcount note undershort_of_channels_tsv. It does not list declined recordings, so the index's failure list is the main source for refusals.ZARR_ENGINE_VERSIONis not bumped (ADR 0033): discovery is unchanged, and refused recordings come back through a targeted requeue.Review round 1
One commit per finding, all rebased on
origin/dev.Let the fidelity sweep read the overcount note).backend/src/services/zarr-fidelity-sweep.tsflaggedchannel_count_mismatchwhenever a store's total was below its channels.tsv, so the stores this PR newly serves (on003645's 108 EEG recordings, 75 vs 404) would have been marked failed and lefthas_zarr_verifiedfalse; the same was already true for FIF/EDF since 0.10.9 and for on000117. A store short of its sidecar is now not a mismatch when its own index entry carries achannels_tsv_count_mismatchthat parses against the shared zod schema and hasin_store == in_file ==the store's channel total. A store short of its header, short of the sidecar with no disclosure, with a malformed disclosure, or with a disclosure that does not match the served total is still flagged. This is a backend Worker behavior change; it ships with the next release. Tests driverunZarrFidelitySweep: disclosure present and consistent (verified), absent (failed),in_store < in_file(failed), inconsistent with the groups (failed), malformed (failed). Reverting the condition fails the first.data's dims (Stop the EEGLAB header walk at data's dims)._mat5_struct_fieldsskipped pastdatabefore its both-seen check, so a compressedEEGinflated every sample. It now returns as soon as both are read. The regression test writes a compressedEEGwhose deflate stream is real for the header and the first 64 KiB of samples and garbage after; the count comes back, and withnbchanmoved afterdatathe same garbage is reached and the read returns None. The old code fails it.Widen the EEGLAB header memory test margin). The stream chunk is now 64 KiB (it bounded both the compressed input read and each skip step at 1 MiB). The test uses a 51.2 MB inline matrix, withnbchanboth before and afterdata(the latter forces a full skip through the compressed matrix), against a bound of a sixteenth of the samples (3.2 MB). Measured parser peak is under 0.4 MB;loadmatpeaks above 51 MB. This replaces the 19.2 MB / one-third bound described above.Cap bytes an EEGLAB header read may inflate).EEGLAB_MAX_HEADER_READ_BYTES = 256 MiBbounds the bytes one classic header read may inflate or inspect (seeks past uncompressed fields do not count); past it the read returns None with the usual single::warning::. After the fix above, only the fields ahead ofnbchananddataare inflated; in EEGLAB's order the largest istimes, one double per sample. A MAT v5/v7 variable is capped at 2 GiB, so with inline single-precision samplestimesfits under the cap from 15 channels up; a read that reaches it (for example a very long.fdt-backed recording) is only unknown, the gate it had before this PR. Tested with a zlib bomb that declares cap + 1 MiB of zeros ahead ofnbchanin a file under 2 MB: None in well under a second. The same shape just under the cap still counts.Document why odd EEGLAB nbchan is unknown). A fractional nbchan stays None: biosigIO truncates it for classic files and rounds it for v7.3, so no single integer is what it serves. A new test pins both importer readings of 3.6 (3 and 4) against the parser's None.nbchanbelow the matrix rows also stays None rather than serving as a lower bound: the count is published asin_fileand used as proof of completeness, and a header its own matrix contradicts proves nothing. A v7.3 subtest now covers that case too.Test EEGLAB header on hand-built MAT files). A small in-test writer (Mat5) covers whatscipy.io.savematcannot produce, and every file it writes is cross-checked byscipy.io.loadmatand biosigIO's importer:nbchanas double,uint8orint32(the last two in a small data element, whose tag big-endian files store swapped). Making the small-element unpack little-endian only fails 14 subtests.EEGstruct array: the first element wins, and an inconsistent first element is not rescued by a consistent second;nbchanstored afterdata;EEG, including a large matrix and flatnbchan/datadecoys;SIGALRMguard (1,716 subtests, about 1 s).Round 1 results
test_generate_zarr.py test_zarr_queue.py test_purge_non_raw_stores.py test_find_collapsed_channel_stores.py test_patch_power_line_frequency.py) with biosigio 1.2.10 and mne 1.13.2: 973 passed, 5 skipped (Linux-only RLIMIT and /proc tests), 0 failed.test_hallu_zarr_config.py: 51 passed; the other 74 need bash 4+ and are left to Linux CI. No hallu file is touched.bun test zarr mcp: 884 pass at the root and 684 in backend, includingzarr-fidelity-sweepand its route test.