Skip to content

0.3.0: streamed image writer, band by band (FitsImageWriter<T>) - #14

Merged
sputier merged 1 commit into
mainfrom
feat/13-streamed-writer
Nov 12, 2026
Merged

sputier merged 1 commit into
mainfrom
feat/13-streamed-writer

Conversation

@sputier

@sputier sputier commented Nov 12, 2026

Copy link
Copy Markdown
Owner

Closes #13

Public contract (additive only)

public sealed class FitsImageWriter<T> : IDisposable where T : unmanaged
{
    public static FitsImageWriter<T> Create(string path, FitsHeader header,
        ChecksumPolicy checksums = ChecksumPolicy.Auto, FitsSaveMode mode = FitsSaveMode.Overwrite,
        CancellationToken cancellationToken = default);

    public int RowLength { get; }      // NAXIS1
    public long RowsPerPlane { get; }  // NAXIS2 (1 for a 1-D image)
    public long PlaneCount { get; }    // product of NAXIS3.. (1 for 1-D/2-D)

    public void WriteRows(long plane, long firstRow, ReadOnlySpan<T> rows, CancellationToken cancellationToken = default);
    public void Complete(CancellationToken cancellationToken = default);
    public void Dispose();             // before Complete: abandons the write
}
  • Header first. It holds BITPIX, NAXIS, NAXISn and any other card (BSCALE, BZERO, BLANK, WCS...). The writer copies it and normalizes it as the primary HDU, exactly as Save does for HDU 0. SIMPLE is optional, and an XTENSION = 'IMAGE' header is accepted, so image.Header of an existing ImageHdu can be passed as is.
  • T follows ImageHdu.Create<T>. BITPIX must match T. sbyte, ushort, uint and ulong need the BZERO of the convention (compared exactly) and BSCALE 1. Values are stored values: BSCALE, BZERO and BLANK are cards written as given, not applied. The in-memory path does not apply them either.
  • Rows in file order. A band is whole rows of one plane: plane 0 rows 0..H-1, then plane 1, and so on.
  • Errors abandon the write. Out-of-order rows, a non-whole-row length, an empty band, rows past the plane or after the last one: ArgumentException. Complete with rows missing: InvalidOperationException. Any exception, cancellation or Dispose before Complete deletes the temporary file, publishes nothing and leaves an existing target untouched. Every later call then throws InvalidOperationException.
  • Publication uses the same code as FitsFile.Save(path, ...): a temporary file in the target directory, flush to disk, then an atomic move (File.Replace or Move). CreateNew has the early check plus the final move, which refuses an existing path (with the O_EXCL claim + rename on Unix from Make CreateNew saves atomic on Unix #11), so a file that appears during the write is kept.
  • Checksums. CHECKSUM and DATASUM are summed while the bytes are written, including the fill. Placeholder cards are written up front by the same SetChecksums code, then rewritten in place before publication. The cards are fixed-width, so the header keeps its length (asserted).
  • Memory. One pooled 256 KB conversion buffer, the 64 KB FileStream buffer and the header. The band itself belongs to the caller and is not kept.

Design choices

  • A writer object, not a callback. The caller (a mosaic) owns its loop, its buffers and its parallelism, so a pull callback would invert control for no gain. Create / WriteRows / Complete + Dispose matches FitsFile.Open/Save + using. "Disposed without Complete" is the natural way to say "abandon", and it composes with using and exceptions.
  • A generic class FitsImageWriter<T>. The value type is fixed once and checked against BITPIX at Create, rather than at every call.
  • Explicit plane / firstRow on WriteRows. They are redundant with the internal cursor, which makes them an assertion: a caller bug (skipped, repeated or reordered band) becomes an explicit error instead of a silently shifted image.
  • Strict: any error abandons the write. This is the simplest contract that guarantees "nothing is published" (see the open question below).
  • Reuse, not duplication.
    • Conversion: PlaneDataSource<T>.Encode (made static), i.e. the bytes of the plane-by-plane write.
    • Type mapping: ImageHdu.Describe<T>.
    • Header normalization: ImageHdu.Normalize.
    • Checksum policy and cards: Hdu.PrepareChecksums / SetChecksums.
    • Checksum accumulation: ChecksumStream.
    • Target resolution and publication: FitsFile.SaveTarget / PublishTemporary / PublishNew / TryDelete, extracted from BeginPathSave and PublishSaved with no behaviour change.

Tests (StreamedWriteTests, + astropy)

  • Byte-for-byte identity with FitsFile.Save of the same image and header:

    • all 10 pixel types (byte .. double, unsigned conventions);
    • 2-D and 3-plane images;
    • Auto / Always / Never, with and without stale sums in the header;
    • band heights 1, 5 (not dividing 23) and the whole plane;
    • BSCALE/BZERO + BLANK for the signed integer types, BLANK with ushort, NaN in float/double;
    • large bands spanning several 256 KB blocks, and 300 001-byte rows whose blocks end inside a checksum word;
    • an XTENSION header read from a file, and a header built from scratch without SIMPLE.
  • astropy (verify_with_astropy.py): verify('exception'), verify_checksum / verify_datasum, and values for a float cube with NaN, a scaled int16 image with BLANK (bands of one row), and a uint16 cube written in CreateNew mode.

  • Cancellation:

    • between bands;
    • in the middle of a 64 MB band (a watcher thread cancels once the temporary file holds more than one block);
    • at Complete;
    • before Create.

    Each time: no file left, existing target intact, writer unusable.

  • Publication:

    • the target is untouched until Complete;
    • Dispose before Complete leaves nothing;
    • a missing directory leaves nothing behind.
  • CreateNew:

    • an existing file is refused at Create;
    • a file that appears after Create is kept, and Complete throws FitsFileExistsException (inner IOException from the move);
    • 25 rounds of 8 concurrent writers to the same path: exactly one wins, and the file is the winner's.
  • Errors:

    • order: skipped, repeated, wrong plane, negative row;
    • length: partial row, empty, more rows than left, rows after the end;
    • missing rows at Complete;
    • calls after Complete / Dispose;
    • header checks: BITPIX mismatch, missing or inexact unsigned BZERO (incl. 2^63+1 for ulong), BSCALE ≠ 1, no pixel, missing axis, random groups, BINTABLE, rows longer than an array, unknown enums, unsupported T.
  • Memory: a 2048-wide float image is written in bands of 16 rows with checksums, at 256 rows and at 4096 rows. Thread-allocated bytes for the 4096-row (32 MB) run are about 108 KB (bound: < 512 KB). The two heights differ by less than 16 KB.

Release 0.3.0

  • Version 0.3.0; PackageValidationBaselineVersion 0.2.0 (dotnet pack validates against the published 0.2.0); CHANGELOG; RELEASING.
  • Docs:
    • "Band by band" section in docs/images.md with a compiled and run example, and a pointer in docs/files.md;
    • generated API page;
    • DocGen names generic type pages Type-1.md instead of Type`1.md, and no longer entity-escapes type names inside code spans of the index.
  • tools/verify_package.py: the consumer project also streams an image and checks it is byte-identical to Save.
  • Not tagged, not published.

Validation (local, Windows)

  • dotnet build -c Release: 0 warnings.
  • Tests: 1982/1982 on net10.0 with FITSNET_SKIP_INTEROP=1. Net8 runtime and Python/astropy are not installed locally: the CI matrix runs net8.0, Linux (the O_EXCL path) and astropy.
  • DocGen --check up to date.
  • dotnet format --verify-no-changes clean on the touched C# files (the repo has older whitespace findings elsewhere, left untouched).
  • dotnet pack with package validation, and the verify_package consumer program on net10.0 against the packed 0.3.0: OK.
  • Reviewed by a dotnet-code-reviewer agent; its relevant remarks are applied:
    • docs index escaping;
    • a real mid-band cancellation test;
    • exact BZERO check;
    • documented Auto semantics (sums are always recomputed);
    • Unix CreateNew limits and open-FitsFile caveat documented;
    • memory bound margin;
    • ObjectDisposedException name.

Open questions for the author

  • Strict abandonment on argument errors. An out-of-order WriteRows currently discards everything written so far. The alternative is to validate before writing anything and keep the writer usable after an ArgumentException.
  • Async API. WriteRowsAsync(ReadOnlyMemory<T>) / CompleteAsync are not included; they could follow additively if Asteria needs them.
  • Optional multi-plane band. A band holding several planes at once is not included; the caller writes plane by plane.
  • No physical→stored conversion. Writing floats into an integer BITPIX with BSCALE/BZERO, and NaN → BLANK, is not done. The in-memory path has no such conversion either, so the issue's "BLANK for NaN" is covered as "the caller writes the BLANK value".

🤖 Generated with Claude Code

- FitsImageWriter<T>.Create(path, header, checksums, mode, token) checks the
  header (BITPIX of T, BZERO of the unsigned convention, image with pixels),
  normalizes it as the primary HDU like Save, creates the temporary file next
  to the target and writes the header. WriteRows(plane, firstRow, rows, token)
  takes whole rows of one plane in file order and converts them through one
  256 KB buffer with the encoder of the plane-by-plane write. Complete(token)
  pads the data, fills in the fixed-width CHECKSUM/DATASUM cards summed while
  streaming, flushes and publishes with the path-save code of FitsFile
  (atomic move; CreateNew with the O_EXCL claim on Unix).
- Any failure, cancellation or Dispose before Complete deletes the temporary
  file and leaves the target untouched; out-of-order rows, wrong lengths,
  extra or missing rows are explicit errors and publish nothing.
- Tests: byte-for-byte identity with the in-memory save for every pixel type,
  2-D and 3-plane images, BSCALE/BZERO, BLANK, NaN, checksum policies and
  band heights 1/5/whole plane; astropy checks; cancellation (between and
  within bands, at Complete); CreateNew (existing, race, concurrent writers);
  error cases; allocations independent of the image height.
- 0.3.0: version, changelog, package validation against 0.2.0, docs (guide
  section, example, generated API page; DocGen names generic type pages
  Type-1.md, and no longer entity-escapes names in code spans of the index),
  verify_package.py uses the writer.

Closes #13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sputier
sputier merged commit ce78e8a into main Nov 12, 2026
5 checks passed
sputier added a commit that referenced this pull request Nov 14, 2026
Streamed image writer (FitsImageWriter<T>): header up front, rows written band by band in file order, CHECKSUM/DATASUM accumulated while streaming, same publication guarantees as Save. Release 0.3.0.

Closes #13
@sputier
sputier deleted the feat/13-streamed-writer branch November 14, 2026 21:16
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.

Streamed image writer (band by band) for images larger than memory

1 participant