Skip to content

Phase 9: events.parquet with sample indices - #1205

Merged
neuromechanist merged 13 commits into
feature/issue-1181-epic-zarr-servingfrom
feature/issue-1060-phase9-events-parquet
Sep 2, 2026
Merged

neuromechanist merged 13 commits into
feature/issue-1181-epic-zarr-servingfrom
feature/issue-1060-phase9-events-parquet

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1060
Part of epic #1181

What

Publishes <id>/zarr/events.parquet: one columnar file per dataset, one row per (event, channel group), with sample_index computed by the converter. A client can plan epochs and shards with zero signal bytes read, and the MCP (ADR 0025) gets its get_events source.

index.json gains events_parquet + events_row_count and a layout.events template — all optional, so a dataset with no events (and every index published before this) still validates against the closed v3 schema.

The formula, and why it is published rather than left to clients

sample_index = round(onset_s * rate), ties up, where rate is the group's serving rate (the level-0 rate attr the index already publishes).

  • biosigIO resamples level 0 to target_rate = min(native_rate, cap) via scipy.signal.resample_poly(x, up, down) with up/down = Fraction(round(target), round(native)), trimmed/padded to n_out = round(n_native * target / native) — so level 0 is exactly the grid t[n] = n / target_rate over the source's span. Both exporters share _resample_channel, so the in-memory and streaming paths cannot disagree.
  • resample_poly is zero-phase, so there is no group delay to subtract.

Verified on the real nm000329 (1000 Hz → 250 Hz, sub-1 calibration run, 100 MB BDF, 72 events), through the real convert_recording:

check result
n_samples at level 0 vs round(n_native * 250/1000) 138750 == 138750
filter delay (served level 0 vs native[::4], cross-correlated) peak at lag 0, r > 0.9
published index vs nearest level-0 grid sample max 1 sample, and every one of the 13 disagreements is an exact tie (onset exactly 0.002 s — half a sample — from both neighbours, e.g. 39.302 s → 9825.5); 0 on every non-tie event
published index vs the dataset's own curated native sample column max 1 sample, same ties

nm000329's ratio is an exact 4, which cannot distinguish a formula that assumes integer decimation from one that does not, so a synthetic 512 → 250 case (125/256, real EDF through the real exporter) covers the fractional ratio.

Shape

  • Columns exactly as Publish <id>/zarr/events.parquet with converter-computed sample indices #1060: store_path, subject, session, task, run, onset_s (f64), duration_s (f32), sample_index (i64), group_name, trial_type, value, hed, then the remaining events.tsv columns under their own names — x_-prefixed only on a collision. Every string column is dictionary-encoded; zstd; ordered by store_path, onset_s.
  • One parse feeds both the rows and the per-store n_events / trial_types, which is Publish <id>/zarr/events.parquet with converter-computed sample indices #1060's last acceptance criterion. It also fixed a real bug on the way: nm000329's events.tsv starts with a UTF-8 BOM, which made the first column onset.
  • Bounded memory: rows are staged per store on an anonymous temp file as recordings finish and written store by store through a ParquetWriter — nm000281 is ~25k stores and never becomes one table. An incremental run carries an untouched store's rows forward from the published file, exactly as the index carries its entry.
  • Best-effort like manifest.json: a missing pyarrow, an unreadable prior file, or a failed upload warns, leaves the index naming no file, and reports events_upload_failed on the callback. It never fails a good conversion (ADR 0005).
  • Not clamped to the group length: an onset past the end is a property of the data, and a clamped index would be indistinguishable from an event on the last sample.

Also in here

  • manifest.json lists the events file with its byte size and row count (files[]), so "the object on S3 is the one this run wrote" is a HEAD, not a download.
  • Edge caching bug fixed: manifest.json was getting the 24-hour chunk TTL and no purge, so a re-conversion's manifest could disagree with the fresh index at the edge for a day. index.json, manifest.json and events.parquet now share one ZARR_DATASET_DOCUMENTS list driving both cacheControlFor and zarrPurgeTargets. Only index.json stays always-proxied; the other two redirect to S3 for non-browser clients like any store object.
  • purge_non_raw_stores.py drops the events pointer when its rewrite actually removes entries: the published file still holds rows for those stores, so the count would overstate it.
  • AGENTS.md's Zarr paragraph states the formula, the "index names the file only when it exists" rule, and the one-set cache rule.
  • The callback's events_row_count (nullable) / events_upload_failed are typed on the backend but deliberately not persisted — the row count is served by the index, and a column would spend the datasets budget (ADR 0034) on a number already available.

Review round (three reviewers)

  • Carry-forward defect (reproduced): "carried over" was defined as "produced no rows this run", so a store that WAS reconverted and legitimately has no events kept republishing its stale rows from the prior file, and a first --clean run reported every event-less store as an unrecoverable carry-over. The set of stores actually reconverted is now threaded from record into the publisher and the writer, which never falls back to prior rows for one.
  • Ordering: the index is validated BEFORE anything is uploaded (in the shape it will take, with the deterministic URL and a minimum: 0 placeholder count), so a refused index no longer leaves a freshly overwritten events.parquet that the live index does not describe. The one interleaving that can still overwrite reports events_row_count/events_upload_failed on the failed callback.
  • Per-store signals: a store whose events cannot be positioned (all sample_index null, or events with no channel group) is named in a ::warning:: and counted into a new events_stores_without_rows callback field.
  • Backend: the zarr-ready summary line carries events_row_count, events_upload_failed and manifest_upload_failed, and an unpublished sibling document gets its own console.warn.
  • purge_non_raw_stores.py: the index rewrite is now a CONDITIONAL write. It re-reads the live document with its ETag immediately before writing, recomputes the rewrite from it, and PUTs with --if-match; a 412 is reported as index_rewrite_conflict and the newer document is left alone. Previously a converter run publishing during the (minutes-long) delete was silently reverted, taking every store it had just added with it.

Tests

468 converter tests in test_generate_zarr.py plus 93 in test_purge_non_raw_stores.py (438 and 87 before), 1626 backend tests, all green. pyarrow joins the zarr-python-test install list because the schema/ordering/bounded-write tests are pure Python and belong in that tier; the real stack tier is unchanged.

Mutation-checked one line at a time: the tie rule, the BOM strip, the onset ordering, the per-group fan-out, the row-group flush, the prior carry-forward, record's staging, the index field injection, the schema declaration, the document list, and the callback's nullability each fail the tests that claim them.

Not merged.

Delta re-review

One finding: the converter reported events_stores_without_rows but the backend callback never declared or logged it (the pool_breaks class of drop). Fixed in the final commit: declared on the body and schema, appended to the summary line, and warned when non-zero, with the sibling-document test extended.

One columnar file per dataset at <id>/zarr/events.parquet, one row per
(event, channel group), with the level-0 sample index computed by the
converter -- the only party that knows the exact resampling relation
(#1060). index.json gains events_parquet + events_row_count and a layout
entry; n_events/trial_types now come from the same parse as the rows.

Rows are staged per store on disk as recordings finish and written store
by store into a ParquetWriter, so a 25k-store dataset never builds one
table. An incremental run carries an untouched store's rows forward from
the published file exactly as the index carries its entry.

Best-effort like manifest.json: a missing pyarrow or a failed build/upload
warns, leaves the index naming no file, and reports events_upload_failed
on the callback rather than failing a good conversion.

Tested: converter suite (438), incl. a main()-level clean + incremental
run over a real EDF, and mutation-checked on the formula, the ordering,
the flush, the carry-forward and the schema.
nm000329 (1000 Hz served at 250 Hz) is #1060's acceptance case, and a
fixture built at the serving rate cannot check it: the error class the
column removes only exists when the rates differ. Downloads the recording
and its events.tsv on demand into a cache outside the repo (skipped, never
failed, when offline; NEMAR_ZARR_SKIP_REAL_DATA opts out), converts it
with the real exporter, and checks three things that do not reuse the
formula: level-0 n_samples == round(n_native * target/native), zero filter
delay (served level 0 correlates with native[::4] peaking at lag 0), and
every onset within one sample of the level-0 grid -- exact except on 13
events that sit exactly half a sample between two, where no rule can do
better. The dataset's own native `sample` column agrees on the same terms.

Adds a synthetic 512 -> 250 case (ratio 125/256), since nm000329's exact
4 cannot tell a formula that assumes integer decimation from one that
does not.
The events.parquet writer needs it (#1060), and the schema/ordering/
bounded-write tests are pure Python, so the fast zarr-python-test tier
installs it too -- otherwise those tests do not fail, they skip, and the
converter's "warn and publish no events file" degradation makes a broken
writer look like a dataset with no events. hallu-zarr.sh's fallback spec
is unchanged: the venv installs from requirements.txt.
manifest.json now lists the events.parquet a run uploaded with its byte
size and row count, so "the object on S3 is the one this conversion
wrote" is a HEAD away rather than a download. Not carried over from the
prior manifest: a run that published no file must not claim the previous
run's bytes.
events_row_count (nullable) and events_upload_failed were reaching the
backend through passthrough(), so nothing said what they mean or that
null is a real value. Declared, documented, and tested; deliberately not
persisted -- the row count is served by the published index, and a column
would spend the datasets budget (ADR 0034) on a number already available.
manifest.json was getting the 24-hour chunk TTL and no purge, so a
re-conversion's manifest could disagree with the fresh index at the edge
for a day; events.parquet would have inherited the same gap. One
ZARR_DATASET_DOCUMENTS list now drives both cacheControlFor's short
untokened TTL and zarrPurgeTargets, so the two cannot cover different
files. Only index.json stays always-proxied: the other two redirect to S3
for non-browser clients like any store object.
zarrObjectType's comment points at cacheControlFor, which now covers three
documents while this still labels only index.json -- on purpose, since
"index.json is 95% of egress" is a measurement of index.json.
The canonical zarrPurgeTargets tests live in test/, not backend/test/,
and asserted the old index.json-only list. They now assert all three
documents against the shared constant; the backend cache file keeps only
the cross-module claim (every purged document has the short TTL, no chunk
does), which is the half that belongs beside cacheControlFor.
@github-actions

github-actions Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1205

Version: 0.9.12-PR1205.2390c42
Commit: 2390c42


🤖 Updated on each push.

The published events.parquet still holds rows for the stores the purge
just removed, so events_row_count would overstate it and events_parquet
would name a file describing stores the index no longer lists. Both go
until the next conversion republishes them, which is the same rule the
converter follows.
Three defects in one code path (they do not build apart), all from
review of #1205:

Carry-forward was defined as "produced no rows this run", so a store
that WAS reconverted and legitimately has no events -- its events.tsv
deleted or emptied -- was treated as untouched and had its stale rows
republished from the prior file forever. On a first --clean run the same
definition reported every event-less store as an unrecoverable
carry-over. `reconverted` (every store this run rebuilt, rows or not) is
now threaded from `record` through to the writer, which never falls back
to prior rows for one.

Ordering: the index is now validated BEFORE anything is uploaded, in the
shape it will take (the events pair filled with the deterministic URL
and a `minimum: 0` placeholder count), so a refused index no longer
leaves a freshly overwritten events.parquet that the live index does not
describe. The one interleaving that can still overwrite -- a document
that passes with the placeholder and fails on the real count -- now
reports events_row_count/events_upload_failed on the failed callback,
which is the only place an operator would learn the object was replaced.

Per-store signals: a store whose events cannot be positioned is named
(`::warning::`) and counted into a new `events_stores_without_rows`
callback field -- either every sample_index is null, or the store has
events and no channel group to attach them to. The decision is a pure
helper because the second case cannot be reached through a real
conversion.

Tested: 470 converter tests, incl. a mixed dataset through main() twice,
the refused-index interleavings, an unclamped past-the-end onset, a
failed events upload, duplicate onsets, and a run with pyarrow absent
from sys.modules. Mutation-checked per fix.
The summary line now carries events_row_count, events_upload_failed and
manifest_upload_failed, and an unpublished sibling gets its own warn.
Neither flag has a column and neither fails the run, so without this the
condition -- index.json published while manifest.json or events.parquet
was not -- was visible only in a cron log on one box.
purge_non_raw_stores read index.json, spent minutes deleting objects,
then PUT the rewrite unconditionally -- so a converter run that
published in that window was silently reverted, taking every store it
had just added with it. The live document is now re-read (with its ETag)
immediately before the write, the rewrite is recomputed from it, and the
PUT carries --if-match; a 412 is reported as index_rewrite_conflict for
that dataset and the newer document is left alone. An absent index writes
with --if-none-match, so a first index published meanwhile is safe too.

Both modes now share one planner (plan_live_index_rewrite, renamed from
plan_snapshot_index_rewrite): the snapshot path was already doing this,
the live path had the same exposure on a shorter fuse.

Tested end to end against a real stub aws with md5 ETag semantics: an
uncontested rewrite, a concurrent publish detected and not clobbered, a
store published between the reads surviving, and the absent-index case.

This branch was previously deployed

1 inactive deployment
npm — 2390c424 Deployed Sep 2, 2026 by neuromechanist via publish #2197
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.

1 participant