Skip to content

feat: sanitize is a linter; tfmgr add resumes and never changes data - #14

Merged
oesteban merged 4 commits into
masterfrom
fix/add-sanitize
Dec 2, 2026
Merged

oesteban merged 4 commits into
masterfrom
fix/add-sanitize

Conversation

@oesteban

@oesteban oesteban commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

tfmgr sanitize becomes a linter over the image rules, and tfmgr add becomes resumable and never changes the data it is given.

tfmgr sanitize tpl-X                 # --check (default): list, change nothing
tfmgr sanitize --fix tpl-X           # safe fixes: values and world coordinates kept
tfmgr sanitize --fix-unsafe tpl-X    # also those that rescale, round or move
Rule Problem Fix
TF702 image-orientation sform and qform disagree unsafe: qform := sform
TF703 probseg-range probabilities outside [0, 1] unsafe: clip at 0, divide by the maximum
TF707 not-ras (new) voxel axes not RAS safe: reorient
TF708 oblique (new) rotated axes unsafe: deoblique around the image center
TF709 storage-dtype (new) labels wider than needed; anatomical images stored as float or wider integers safe: uint8/uint16, int16 for integer values; unsafe: int16 with slope and intercept
TF710 image-units (new) units unset (or not mm) safe when unset: mm
TF711 unreadable-image (new) empty, truncated or corrupt file (crashed or passed before); every payload is streamed in full none

When a fix moves the grid of every image of a resolution, sanitize updates that res block (or the cohort override) of template_description.json, so the fix does not introduce TF701.

 tfmgr add X
-  TemporaryDirectory: start over after any failure
-  copy_template: reorient, int16 cast, probseg rescale, deoblique (silently)
-  create_sibling_github(existing="replace")      # deleted and recreated the repo
-  run_command(shell=True), return codes ignored
-  hub fork / hub pull-request; {path.name}.toml; -j ignored
+  <user cache>/tfmanager/tpl-X/state.json: copy > validate > save > gin > github > pull-request
+  copy byte for byte (--fix / --fix-unsafe: sanitize the copies)
+  validate --mode strict --level content: errors stop before any upload
+  existing="reconfigure"; on_failure="stop"; run_command raises
+  gh repo fork / gh pr create; tpl-<ID>.toml; push jobs = --nprocs
+  SPDX license prompt; LICENSE gets its SPDX-License-Identifier header

Evidence

  • Before: tfmgr sanitize called copy_template(dir, normalize, force_dtype, deoblique) against copy_template(path, normalize, deoblique, force_dtype), so the two flags were swapped. Its deoblique multiplied a 3×3 by a 4×4 matrix, and an empty image crashed validate --level content.
  • After: 161 tests pass (31 new):
    • image fixes on synthetic images: world coordinates are kept by reorientation, and the int16 rounding error stays within slope/2;
    • sanitize keeps res blocks in step, leaves a block alone when its images disagree, and never writes into annex objects;
    • add with DataLad, git and gh mocked: it resumes after a failed GIN push without repeating any step, does not duplicate an open PR, restarts from the copy when the source changes, and stops before uploading when validation finds errors;
    • the source fingerprint hashes contents (an edit that keeps size and modification time restarts from the copy), and sanitize exits 2 without nibabel instead of reporting a clean template.

tfmgr sanitize --check on the local MNI152NLin2009cAsym data turns up real problems for WP5:

TF701 grid-mismatch     tpl-MNI152NLin2009cAsym_res-01_desc-head_mask.nii.gz: shape [545, 653, 545] (res-01 says [193, 229, 193])
TF704 dseg-values       tpl-MNI152NLin2009cAsym_res-02_desc-carpet_dseg.nii.gz: Non-integer values (float64)
TF710 image-units       ..._res-01_seg-aseg_dseg.nii.gz: Spatial units are not set (fix: mm)   [fix] x18
TF709 storage-dtype     ..._atlas-Schaefer2018_..._dseg.nii.gz: Labels stored as int16 (fix: uint8)   [fix] x17

Merge Danger

Door: two-way

Blast Radius: contributors

tfmgr sanitize without flags no longer writes anything, and --normalize, --force-dtype and --deoblique are gone. tfmgr add needs gh instead of hub, refuses templates that fail strict validation, and leaves its work directory in the cache until it is removed.

oesteban and others added 2 commits December 2, 2026 20:47
tfmanager/images.py inspects a NIfTI image (TF702, TF703, TF707-TF710) and
applies the fixes of its problems. A safe fix keeps the values and the
world coordinates of every voxel (reorient to RAS, units to mm, labels to
the smallest unsigned integer type, integer-valued images to int16); an
unsafe one changes values or moves the image (rescale probabilities,
deoblique, qform := sform, float images to int16 with slope and
intercept). Issues carry `autofix`, shown as [fix] / [fix-unsafe].

New rules: TF707 not-ras, TF708 oblique, TF709 storage-dtype, TF710
image-units (all info in legacy mode) and TF711 unreadable-image, which
replaces a crash on empty or truncated images. TF505 suggests a LICENSE
header only for a valid SPDX expression.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- `tfmgr sanitize` lists the image problems (--check, the default), applies
  the safe fixes (--fix) or all of them (--fix-unsafe), and updates the res
  blocks of template_description.json when every image of a resolution
  moved alike. Annexed images are replaced by regular files. The silent
  int16 cast, probseg rescaling and --normalize are gone, and the swapped
  positional arguments with them.
- `tfmgr add` (tfmanager/add.py) runs copy, validate, save, gin, github and
  pull-request steps, recorded in <workdir>/state.json (default: the user
  cache directory) so a failed run resumes; a changed source restarts from
  the copy. The copy is byte for byte (--fix/--fix-unsafe apply sanitize to
  it), strict content validation stops it before any upload, commands and
  DataLad calls stop on failure, siblings are reconfigured (never
  replaced), gh replaces hub, the intake file is tpl-<ID>.toml, --nprocs is
  honoured, and the license is an SPDX expression written as the LICENSE
  header. Prompted answers are kept for the next run.
- utils.copy_template is removed; io.run_command takes argument lists and
  raises on failure. platformdirs joins the [add] extra. The ruff config
  uses a table for per-file ignores (old pips cannot parse the inline one).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@oesteban
oesteban marked this pull request as ready for review December 2, 2026 19:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T19:55:36.564774Z f89edb8 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f89edb86ee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tfmanager/validate/content.py Resolved
Comment thread tfmanager/add.py Resolved
Comment thread tfmanager/sanitize.py
def lint(root: str | os.PathLike) -> list[Issue]:
"""The image problems of the template at ``root`` (errors and warnings)."""
issues = run_checks(_context(Path(root)))
return [i for i in issues if i.code.startswith(PREFIX) and i.severity != 'info']

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fail when sanitize cannot load image dependencies

When nibabel or numpy is unavailable, the content validator reports TF700 as informational, and this filter removes it. tfmgr sanitize then reports no problems and exits successfully without inspecting images; the CLI's ImportError handler does not run because the validator swallowed the error. Preserve the missing-dependency report or fail the command.

Useful? React with 👍 / 👎.

Comment thread tfmanager/images.py
'TF709', f'Labels stored as {dtype} (fix: {target}).', 'safe', 'labels'
)
)
elif anatomical and np.issubdtype(dtype, np.floating):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Check integer anatomical images for TF709

When an anatomical NIfTI is stored as int32 or int64, this branch only handles floating-point storage, so it emits no TF709 even when all values fit in int16. As a result, sanitize --fix and tfmgr add --fix leave these images in wider storage despite the advertised rule. Check integer storage too and offer an exact cast when the values fit.

Useful? React with 👍 / 👎.

oesteban and others added 2 commits December 2, 2026 21:49
From the review of #14:
- TF711: nibabel reads lazily, so an image whose voxels no rule reads (MD,
  boldref...) passed with a truncated payload. Every NIfTI is now streamed
  (decompressed in chunks, not held in memory) and its length checked
  against the header.
- tfmgr add fingerprints the source by content: an edit that keeps size
  and modification time (cp -p) restarts from the copy.
- tfmgr sanitize exits 2, and tfmgr add stops, when nibabel is missing,
  instead of reporting a clean template (TF700 was filtered out as info).
- TF709 also flags int32/int64 anatomical images whose values fit int16
  (safe fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@oesteban
oesteban merged commit e4b0b9c into master Dec 2, 2026
6 checks passed
@oesteban
oesteban deleted the fix/add-sanitize branch December 2, 2026 20:56
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