Skip to content

Fix create_zarr deleting and then leaking its temporary store - #289

Merged
JoOkuma merged 1 commit into
royerlab:mainfrom
ieivanov:fix/create-zarr-temp-dir
Oct 9, 2026
Merged

JoOkuma merged 1 commit into
royerlab:mainfrom
ieivanov:fix/create-zarr-temp-dir

Conversation

@ieivanov

@ieivanov ieivanov commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When store_or_path is None (and no default_store_type is given), create_zarr backs the array with tempfile.TemporaryDirectory() but keeps no reference to that object. CPython cleans it up as soon as create_zarr returns:

  1. The directory, with the array's zarr.json, is deleted before the caller gets the array.
  2. The first chunk write recreates the directory (chunks only, no metadata).
  3. Nothing removes it again.

This affects every default-store caller: Tracker.to_zarr / tracks_to_zarr, array_apply, copy_segments, labels_to_contours, register_timelapse, timelapse_flow. Two consequences:

  • Leaked directories. On clusters where $TMPDIR outlives a job (node-local scratch shared across a user's jobs), they pile up. We found nine on one GPU node, three per tracking run.
  • Unreadable arrays. They can't be reopened by path, e.g. from another process, because their metadata is gone.
arr = create_zarr((4, 8, 8), np.uint16)
os.path.exists(arr.store.root)   # False: already deleted
arr[:] = 1                       # recreates the directory (chunks only)
del arr; gc.collect()
os.path.exists(root)             # True: leaked

Fix

Create the directory with tempfile.mkdtemp() and remove it with weakref.finalize(array, shutil.rmtree, ...), so it lives exactly as long as the returned array. The docstring said a MemoryStore is used in this case, which was never true; it's corrected.

Tests

  • New test_create_zarr_temporary_store_lives_with_the_array: the store reopens with zarr.open_array while the array is alive, writes read back, and the directory is gone after del + gc.collect(). On main it fails with FileNotFoundError when reopening.
  • ultrack/utils/_test/test_utils_array.py + ultrack/core/export/_test: 33 passed. pre-commit hooks pass.

Found while making Biohub/biahub#413 run tracking in a per-FOV scratch directory, where biahub currently works around this by pointing tempfile into that directory. Independent of #288.

🤖 Generated with Claude Code

With no store_or_path, create_zarr backed the array with a
tempfile.TemporaryDirectory it kept no reference to, so the directory was
removed as soon as the function returned, taking the array's zarr.json with
it. The first chunk write recreated the directory, which was then never
removed: arrays from to_zarr, array_apply and friends piled up in $TMPDIR,
and nothing could reopen them by path.

Create the directory with mkdtemp and remove it with weakref.finalize when
the returned array is garbage collected.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@ieivanov
ieivanov marked this pull request as ready for review October 9, 2026 20:11
@codecov

codecov Bot commented Oct 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@5c94d84). Learn more about missing BASE report.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #289   +/-   ##
=======================================
  Coverage        ?   83.15%           
=======================================
  Files           ?       98           
  Lines           ?     6294           
  Branches        ?        0           
=======================================
  Hits            ?     5234           
  Misses          ?     1060           
  Partials        ?        0           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JoOkuma JoOkuma left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@JoOkuma
JoOkuma merged commit afbe2d6 into royerlab:main Oct 9, 2026
11 of 12 checks passed
@ieivanov
ieivanov deleted the fix/create-zarr-temp-dir branch October 16, 2026 20:52
ieivanov added a commit to Biohub/biahub that referenced this pull request Oct 16, 2026
create_zarr's default temporary store was deleted on return and then
recreated by the first chunk write, never to be removed, so every
tracking job leaked orphan chunk directories into the worker's $TMPDIR.
royerlab/ultrack#289 ties the store's lifetime to the array. Not in a
PyPI release yet; same revision as #413.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
ieivanov added a commit to Biohub/biahub that referenced this pull request Oct 16, 2026
* feat(track): optional sibling filter for short false divisions

Add `min_sibling_length` to the track settings (default off). When set, at
each division drop a daughter track of that many frames or fewer and merge
the other daughter into the parent (ultrack filter_short_sibling_tracks,
same meaning), in the tracks CSV and the labels, before writing. The
relabeled copy is kept in memory (ultrack's default temporary directory is
never removed) and rows are sorted by track and time.

Most false divisions in the A549 benchmark against TrackEdit annotations
were 1-2-frame daughters (virtual-staining hallucinations, neighbours linked
as daughters). On the four annotated 2026_04_28 FOVs with the mantis-v2 A549
config, min_sibling_length 3 raised division F1 from 0.58 to 0.64 (precision
0.44 -> 0.55, recall 0.84 -> 0.77). Enabled with 3 in the mantis-v2 A549
track config; documented (commented out) in the example settings.

* docs(track): state when the sibling filter keeps a division

ultrack's filter_short_sibling_tracks only acts when exactly one daughter is
short and does not divide again; two short daughters keep the division. Say
so in the setting, the A549 pipeline config and the example, and report the
measured effect of the A549 config on the annotated 2026_04_28 FOVs next to
the benchmark range.

* feat(nextflow): A549 track config segments a 60-plane phase-focus window (#418)

The mantis-v2 A549 track config averaged all Z planes before cellpose, adding
out-of-focus signal. Use biahub's focus window instead: 60 planes around the
in-focus plane found on Phase3D (1/3 below, 2/3 above), with Phase3D loaded
only for focus finding. Sizes are unchanged: smaller cellpose/ultrack sizes
helped mock wells but added false divisions in infected wells.

Measured against TrackEdit annotations, with min_sibling_length 3:
- 2026_04_28 (4 FOVs, 78 divisions): division F1 0.63 -> 0.68 (mock 0.65 ->
  0.70, DENV 0.58 -> 0.63), fewer predicted divisions (107 -> 102) and
  fragmented tracks (396 -> 376).
- 2026_04_21 (5 FOVs, independent, 38 divisions): same mitotic-cell
  detection as all planes (0.95) and division recall (19/38), with fewer
  predicted divisions (92 -> 80) and tracks (422 -> 382).
A 40-plane window scored higher on 04_28 (whose annotations were curated
from a 40-plane run) but lost mitotic cells that drift in Z on 04_21 (0.89).
Peak memory unchanged (~15 GB); focus finding adds ~40% run time. A test
checks the config parses against the current schema.

* build(deps): pin ultrack to royerlab main at the #289 merge

create_zarr's default temporary store was deleted on return and then
recreated by the first chunk write, never to be removed, so every
tracking job leaked orphan chunk directories into the worker's $TMPDIR.
royerlab/ultrack#289 ties the store's lifetime to the array. Not in a
PyPI release yet; same revision as #413.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor(track): drop the MemoryStore workaround in filter_short_siblings

With ultrack pinned past #289 the default store is removed with the
array, so the in-memory store is no longer needed to avoid a leak.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Ivan Ivanov <ivan.ivanov@czbiohub.org>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
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.

2 participants