Skip to content

feat: integrate the NWB source queue with the export worker - #221

Open
tabedzki wants to merge 32 commits into
masterfrom
t3/nwb-gui-data-selection
Open

tabedzki wants to merge 32 commits into
masterfrom
t3/nwb-gui-data-selection

Conversation

@tabedzki

@tabedzki tabedzki commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Bring the existing NWB worker stack onto current master and extend its DataJoint queue to accept registered sessions and manual source selections.
  • Use the queue-assigned nwb_job_id for new outputs and retain existing filenames for older exports.
  • Include an in-place, previewable schema migration and rollout instructions.

Review and rollout

This integration PR targets master and includes worker changes already under review in #112 and its dependencies. The queue integration itself is in 20eb6833 and d902d735.

Companion frontend: https://github.com/BrainCOGS/tech_calendar_streamlit/pull/221. Install the migrated queue and updated worker before rolling out the frontend.

Verification

  • 232 targeted backend tests passed. The 19 legacy DB tests use the pre-migration contract and were deselected.
  • Disposable MariaDB verified job ID allocation, transaction rollback, status logging, migration, and compatibility with older filenames.

CI follow-up

Fixes #222. In a base-only environment, the DANDI client tests reproduced the collection error before the fix. The client now loads NeuroConv when an upload starts, and the Python 3.13 CI job installs the NWB extra so it exercises the conversion tests.

The base suites passed on Python 3.12 and 3.14 with 1,027 tests each.

Assisted-by: Codex:gpt-6.2-sol

tabedzki and others added 30 commits June 12, 2026 08:54
This introduces the previously-uncommitted NWB export pipeline that had
only existed as untracked files in a developer working tree. It adds:

- nwb_production schema (NwbExportJob / NwbExportModality / status and log
  tables) plus nwb_production_utils and nwb_export_enums helpers.
- NwbExportHandler state machine (automatic_job/nwb_export_handler.py) that
  drives jobs through the export lifecycle.
- Cronjob workers (cronjob_nwb_export.py and cronjob_nwb_export_enhanced.py)
  that invoke the handler.
- The nwb_export package (config, credentials, DANDI upload/eligibility/retry,
  modality service, readiness check, error capture, output validation).
- Operational scripts (run_nwb_export.py, migrate_nwb_production_schema.py),
  a production demo notebook, the tests/nwb_export suite, and the
  specs/001-nwb-export-handler design docs.

Committed as-is to establish a baseline; schema reconciliation follows in a
stacked PR.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The NWB export handler and helpers referenced columns and tables that do
not exist in the deployed nwb_production schema. This reconciles them to
the authoritative schema (u19_pipeline/nwb_production.py).

Changes:
- status_nwb_id -> status_id: the active-jobs query and per-job status read
  in pipeline_handler_main, and the update1 in update_status_pipeline, now use
  the real NwbExportJob.status_id (FK to NwbExportStatus).
- Part-tables -> NwbExportModality: process_data_validation (handler) and
  estimate_total_size (nwb_production_utils) no longer query the nonexistent
  NwbExportJob.BehaviorExport/.EphysExport/.ImagingExport part-tables. They now
  query NwbExportModality & {"nwb_job_id": ...} and branch on modality_name
  ('behavior'/'ephys'/'imaging'), parsing probe_numbers/fov_numbers (JSON-array
  strings) and deriving session/recording/scan keys from the NwbExportJob record.
- Log column names: NwbExportLogStatus insert now uses status_old/status_new/
  status_timestamp (was status_nwb_id_old/status_nwb_id_new).
- Non-unique id fetch: submit_nwb_export_job no longer fetch1("nwb_job_id") by
  session_key alone (a session can have multiple jobs). It now fetches by
  {**session_key, "job_name": job_name} ordered by nwb_job_id DESC.

State-machine behavior is otherwise unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
… flow

Completes the cronjob export handler that PR #90 only reconciled to the schema.

1. Recording/scan key derivation (handler + nwb_production_utils): the job record
   carries only the acquisition.Session key, not recording_id/scan keys, so the
   old `{k: job[k] for k in recording.Recording.primary_key}` collapsed to {} and
   matched every recording (vacuous pass). Now resolves recording_id(s) via the
   new recording_ids_for_session() helper (recording.Recording.BehaviorSession).
   Applied to both the ephys and imaging branches; imaging fails loud (Scan<->
   session linkage not yet confirmed) instead of silently passing.

2. process_nwb_conversion: no longer raises NotImplementedError. Conversion logic
   is extracted into the shared module u19_pipeline/nwb_export/conversion.py
   (build_source_data / query_metadata / run_conversion_to_file, ported from
   run_nwb_export.py), so the CLI and cronjob share one code path. Input paths are
   resolved via resolve_input_paths() (export_params or NWB_EXPORT_DATA_ROOT) with
   an actionable error when unresolved.

3. process_validation: removed the broken stub that inserted a validation record
   then raised NotImplementedError (which duplicate-key-crashed on retry). Now runs
   a real HDF5 integrity check + optional NWB Inspector, records truthful results,
   and inserts the row idempotently (replace on retry).

4. Status flow reconciled to NwbExportStatusEnum (QUEUED->DATA_VALIDATION->
   PROCESSING->VALIDATION->[UPLOAD]->COMPLETED). The old handler treated status 3
   as completion, conflicting with the enum (VALIDATION=3, COMPLETED=6) and
   run_nwb_export.py. Added process_upload for the optional DANDI stage (no-DANDI
   jobs go straight to COMPLETED; requested uploads use DandiUploadClient and fail
   loud if credentials are missing).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…off plan

Ports getSyncInfo.cpp + SyncImagingBehavior.m to Python (tifffile-based),
verified against a real ScanImage session. Adds the sync mechanism write-up,
the NWB imaging-export feasibility plan (issue #111), and the coordinator
handoff document.

Assisted-by: ClaudeCode:claude-fable-5
The spike passes: TowersNWBConverter, ScanImageImagingInterface and our
behavior-clock timestamps coexist, and a real conversion of the sample
session puts trial 1's first imaging frame 22.3 ms after trial 1 starts.

Getting there surfaced defects in tank-lab-to-nwb (one sync array applied to
every interface, a hard MATLAB requirement, and a tz-aware/naive subtraction)
plus the block-vs-session clock zero, which costs 27 ms if missed.

Assisted-by: ClaudeCode:claude-opus-5
…fset

trial.start rides ViRMEn's vr.timeElapsed, which the engine zeroes at firstTic
- after vr.code.initialization has already stamped both session.start and
block.start. NWB zeroes at session.start, so every timeElapsed-based quantity,
imaging timestamps included, needs the block-vs-session shift.

The shift is struct allocation plus log-file I/O between two clock calls, so it
varies per session and has to be read from each log rather than hardcoded.

Also records why wall clocks can't do this job: reconstructing the zero through
the imaging PC's epoch stamp lands 958 ms out, which is the inter-machine skew
that motivates content-based I2C sync in the first place.

Assisted-by: ClaudeCode:claude-opus-5
validate_imaging_data_exists referenced imaging_element.Scan and
imaging_element.FieldOfView, neither of which exists -- imaging_element is
element_calcium_imaging.imaging_preprocess. It now walks the real chain,
ImagingPipelineSession -> AcquiredTiff -> TiffSplit -> TiffSplit.File, and
takes a recording key so callers resolve session -> recording_ids the same way
the ephys validator does.

An empty fov_numbers list now requires at least one TiffSplit to exist rather
than passing vacuously: an empty DataJoint restriction matches every row, which
is what made the old code report success for sessions with no imaging at all.

estimate_imaging_size_gb computed 0.05 GB/FOV, more than 10x short for raw
stacks. It now derives bytes from fov_pixel_resolution_xy and the frame counts
in TiffSplit.File, at 2 bytes/pixel for ScanImage int16, and falls back to
0.5 GB/FOV only when the lookup fails. estimate_total_size's imaging branch no
longer skips: the Scan-to-session linkage its TODO was waiting on is the same
recording_ids_for_session hop the ephys branch above it already uses.

Assisted-by: ClaudeCode:claude-opus-5
Replaces the stale imaging validator tests, which mocked the nonexistent
imaging_element.Scan/FieldOfView tables, with tests against the real TiffSplit
chain. Pins the vacuous-pass bug from both sides so an empty fov_numbers list
cannot silently report success again.

The conversion-side tests describe path resolution and the imaging source_data
entry, which are not implemented yet, so two of them fail by design until that
lands.

Assisted-by: ClaudeCode:claude-opus-5
Covers the handler's stage flow, the six-step recipe for adding a modality, the
imaging specifics (deferring to imaging_behavior_sync.md for the sync and clock
details), and the tank-lab-to-nwb dependency, which is path-installed and
unpinned and so has to move in lockstep with this repo.

Records the clock convention as policy: imaging-only sessions use the ViRMEn
clock, and the block-vs-session offset is computed per session rather than
hardcoded. Mixed ephys+imaging sessions stay an open question, flagged for
sign-off before the first DANDI upload, since ephys currently aligns behavior
onto the ephys clock instead.

Assisted-by: ClaudeCode:claude-opus-5
resolve_imaging_paths maps a session or recording key through TiffSplit and
TiffSplit.File to absolute TIFF paths, in acquisition order -- the ScanImage
interface treats a multi-file list as one continuous recording, so unordered
paths would produce unordered frames. The root join is done inline rather than
via element_interface.find_full_path, since element-interface is in the
optional "pipeline" extra and this helper should import without it.

imaging_timestamps_for_session runs the I2C sync and applies the
block-vs-session offset, read per session rather than assumed, then strides the
per-frame array down to whatever sample count the interface reports -- a
volumetric fastZ stack exposes volumes, not pages. A frame count that is not a
whole multiple of the sample count now raises instead of silently misaligning.

build_source_data gains an imaging branch, and run_conversion_to_file passes
imaging timestamps through the converter's new per-interface aligned_timestamps
rather than the shared sync_timestamps array.

The handler's imaging branch no longer raises "not yet wired": it takes the
same session -> recording hop as ephys and calls validate_imaging_data_exists.

The path-resolution test's mock gains __mul__: tiff_split_directory is on the
TiffSplit master and tiff_split_filename on the Part, so resolving a path needs
the join and not just a restriction.

Assisted-by: ClaudeCode:claude-opus-5
Also records what is not verified: the session -> recording -> TiffSplit hop
has only mocked coverage, since no DataJoint instance was reachable, and the
end-to-end run supplied TIFF paths directly to bypass it.

Assisted-by: ClaudeCode:claude-opus-5
A mesoscope session has one TiffSplit per field of view, and fields of view are
separate regions of tissue rather than continuations of one another. The
previous code flattened every split's files into a single ScanImageImaging
entry, which presented unrelated regions as one continuous recording and
misaligned every field of view after the first.

resolve_imaging_paths_by_fov groups the same resolution by tiff_split, and
build_source_data emits ScanImageImagingFOV<n> per field of view, each with its
own timestamps computed from its own files. An explicit tiff_paths override
still names exact files and stays a single interface.

Assisted-by: ClaudeCode:claude-opus-5
The two modalities are not acquired in the same session, so the conflict
between the ephys clock and the ViRMEn clock cannot arise. Records the
condition under which the question would come back rather than dropping it.

Assisted-by: ClaudeCode:claude-opus-5
The I2C packet's third field is the per-trial iteration counter, not ViRMEn's
global one: logTick assigns obj.currentIt, writes trial.time at that index, and
returns the same number for broadcast, all in one call. Indexing trial.time
with the global counter instead would be badly wrong, so the reasoning and its
confirmation on the sample session are worth keeping.

Also notes what the packets do not give: most frames carry none, and the packet
marks when ViRMEn computed the iteration rather than when it was displayed.

Assisted-by: ClaudeCode:claude-opus-5
Once per trial, the iteration that ends the trial does its end-of-trial work
after vr.timeElapsed is stamped and before the I2C packet is sent, so that one
packet reaches ScanImage 200-450 ms after the time the behavior log records
for it. A plain least-squares fit lets those packets drag the slope: on the
sample session's first file it reported +28 ppm drift where the long-baseline
figure is about +5 ppm.

The late-packet tests fail against the current plain fit. The rest cover
corner cases the fit must keep handling: zero scatter, frames with no packet,
zeroed or out-of-range indices, multiple blocks, and two or fewer usable
packets.

Assisted-by: ClaudeCode:claude-opus-5-5
The iteration that ends each trial runs logEnd, endVRTrial and the performance
plot update after vr.timeElapsed is stamped and before updateDAQSyncSignals
sends its packet, so that packet reaches ScanImage 200-450 ms after the time
the log records. The logged time is correct; the packet is late. A plain
least-squares fit let these ~1-in-130 packets drag the slope and inflate the
residual.

The fit now rejects packets more than max(5 MAD, 5 ms) from the line and
refits, never dropping below two points. On files 1-3 and 40 of the sample
session, drift comes out at about +5 ppm with 1.1 ms scatter; the +28 ppm and
10.4 ms reported before were artifacts of a short baseline and one late
packet. A fit on files 1-3 predicts file 40, 25 minutes later, to within 1.9
ms. Frame 644's placement moves by 0.4 ms.

Docs now carry the corrected figures, the multi-file continuity checks, and
the call-order explanation.

Assisted-by: ClaudeCode:claude-opus-5-5
Checked on the full sample session (45 files, 179 trials). The first iteration
of every trial is slow: ViRMEn records the time, sets up the trial, then sends
the packet, so iteration 1's packet arrives a median 8.9 ms late (trial 1:
23.2 ms). Frame timestamps come from the clock fit and are unaffected, but
spans that assign frames by which header received a packet start one frame
late in 100 of 179 trials (two frames for trial 1).

NWB export does not write those spans, so it is unaffected; the docs now say
to derive frame membership from timestamps. Also withdraws the earlier claim
that trial 1's +22.3 ms showed the 27 ms session offset to be physically right;
the offset stands on the shared-zero argument alone.

Assisted-by: ClaudeCode:claude-opus-5-5
Two bugs in the imaging export, found on the full sample session:

- A recording that stops partway through its last fastZ volume (89,508
  pages = 5 x 17,901 + 3) raised ValueError, because the timestamp code
  required the page count to be a whole multiple of the volume count.
- Two fields of view wrote the same TwoPhotonSeries name, so the NWB build
  failed on the second one.

These tests describe the replacement: one interface per field of view and
plane, each with a unique metadata_key and its own page timestamps, keeping
only complete volumes as neuroconv's per-plane reader does. The integration
tests run a real conversion against ~/neuro-data and skip where the sample
recordings or the NWB stack are absent.

Assisted-by: ClaudeCode:claude-opus-5-5
File 45 was recorded after behavior ended, so it carries no I2C packets and
cannot be synced on its own; the export always syncs every file of a field of
view. Files 44 and 45 together still end partway through a volume (3,508 pages
= 5 x 701 + 3).

Assisted-by: ClaudeCode:claude-opus-5-5
Two bugs broke imaging export on real sessions:

- The timestamp code subset one volumetric series with a stride and required
  the page count to be a whole multiple of the volume count, so any recording
  that stopped partway through its last fastZ volume raised ValueError. The
  full sample session does (89,508 pages = 5 x 17,901 + 3).
- Every field of view shared neuroconv's default metadata_key and wrote the
  same TwoPhotonSeries name, so a second field of view failed.

Each field of view and plane is now its own interface,
ScanImageImagingFOV{f}Plane{k}, with a unique metadata_key and plane_index.
The I2C sync runs once per field of view (page_timestamps_for_session), and
plane_timestamps gives plane k every n-th page over complete volumes only,
matching neuroconv's per-plane reader. Planes keep their own page times instead
of sharing one per volume, which within a 5-plane volume at 50 Hz differ by up
to 80 ms. The plane count is read from the TIFF header (actualNumSlices, since
numSlices can be stale); multi-channel and slow-stack files are refused.

The full 45-file sample session now converts: five planes of 17,901 samples,
unique series and imaging-plane names, planes one frame (19.92 ms) apart.

Assisted-by: ClaudeCode:claude-opus-5-5
Replaces the volumetric [::5] subsetting description with the per-plane series,
naming and complete-volume rule, refreshes the stale wiring snapshot in
nwb_export.md, and points the historical smoke-test and handoff notes at it.

Assisted-by: ClaudeCode:claude-opus-5-5
Frames recorded before behavior starts or after it ends cannot be tied to any
part of the experiment. These tests define the window as the first through
last page whose I2C packet maps to a trial present in the behavior log:
inter-trial intervals and packet-less stalls inside it are kept, while
leading and trailing frames, and packets for an aborted trial missing from the
log, fall outside. Each plane keeps the samples whose pages fall in that
window; a plane left with none raises.

Assisted-by: ClaudeCode:claude-opus-5-5
A trial's first packet is sent after trial setup, a median 9 ms late and 23 ms
for trial 1 of the sample session, so bounding the window by the first page
that received a packet dropped the frames in which behavior actually began.
The window is now defined as the pages containing the first and last logged
iterations on the fitted clock. Adds a late-first-packet regression, a check
that the full session's kept frames start at most one frame before trial 1's
first iteration, and an NWB build with trimming on (which failed: the sliced
extractor lacked attributes the ScanImage interface reads).

Assisted-by: ClaudeCode:claude-opus-5-5
Frames recorded before the first trial or after the last cannot be tied to any
part of the experiment. On the sample session that is 12.8 s before behavior
and 43.4 s after, including all of the last file. imaging_alignment now
returns, per interface, the sample range from the frame in which the first
logged iteration falls through the frame in which the last one falls, with
timestamps cut to match; run_conversion_to_file passes both to the converter.
export_parameters['trim_imaging_to_behavior'] = False keeps every frame.

The window is found by time on the fitted clock (behavior_page_window), not by
packet arrival: a trial's first packet is sent after trial setup and lands a
median 9 ms late (23 ms for trial 1), which would have dropped the frames in
which behavior began. Pages are matched with a 1 us tolerance so an iteration
exactly on a page start stays in that page despite fit round-off.

behavior_times_by_page now holds the page-to-trial lookup shared with the clock
fit, and skips block or trial numbers beyond the log rather than indexing past
them.

Assisted-by: ClaudeCode:claude-opus-5-5
Assisted-by: ClaudeCode:claude-opus-5-5
The export computed per-plane frame times here and handed them to
TowersNWBConverter(aligned_timestamps=..., sample_ranges=...). That
argument only existed in tank-lab-to-nwb#1, which was closed: the merged
converter aligns imaging itself from the I2C packets in the TIFF headers,
matches the production MATLAB sync frame for frame, and verifies the file
it writes. Its TowersNWBConverter takes no imaging keys.

Imaging jobs now find their inputs and call the converter:

- resolve_imaging_tiffs: TiffSplit.File rows to paths, taking the
  original stack from originalStacks when the rows are per-ROI split
  copies. One recording per file; fov_numbers can't pick a subset,
  because the converter writes every field.
- resolve_suite2p_dirs: finished ProcessingTask output folders, one per
  tiff_split, with paramset_idx to choose among several runs.
- with_imaging_modality: IMAGING_RAW writes raw TIFFs and
  IMAGING_PROCESSED writes Suite2p results. Both at once are refused.
- converter_metadata: experimenter, sex and date of birth from the DB.
- Imaging together with ephys is refused until one clock rule covers
  both (#111).

The per-plane timestamp code, its tests and the superseded handoff and
plan docs are removed. imaging_behavior_sync.py stays for the DataJoint
sync table.

tank-lab-to-nwb is now the optional `nwb` extra, pinned to the commit
that also clears partly imaged trials (tank-lab-to-nwb#13). uv doesn't
take a dependency's sources or constraints, so the ndx-tank-metadata tag
and zarr<3 are repeated. The converter supports Python <3.14, so the
extra is marked for it.

Assisted-by: ClaudeCode:claude-opus-5-5
Assisted-by: Codex:gpt-6.2-sol
Reuse the 001 worker and preserve legacy jobs while making registry identifiers optional. Validate the exact source snapshot on the worker before conversion.

Assisted-by: Codex:gpt-6.2-sol
Assisted-by: Codex:gpt-6.2-sol
Load NeuroConv only during a DANDI upload and exercise the missing dependency path in the base test suite. Install the NWB extra in the existing Python 3.13 CI job so conversion tests run with required extras.

Assisted-by: Codex:gpt-6.2-sol
@tabedzki
tabedzki marked this pull request as ready for review November 27, 2026 03:33
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.

[BUG] NWB upload client breaks base and pipeline test collection

1 participant