# Stream a scientific raster exchange

This independent example exchanges known-height, unsigned, single-component integer rasters with Pt=0 and identity sample mapping. Input is binary P5 PGM or row-major U16 raw in explicit little- or big-endian order. Calibration is a linear user declaration using exact decimal strings. The host writes the same `moonjls.raster-exchange/v1` sidecar and canonical little-endian U16 reconstruction as the bounded example. [Bounded browser exchange](../raster-restore/README.md) · [Application profile](../../docs/RASTER_EXCHANGE.md)

Copy `moon.mod`, `moon.pkg`, `main.mbt`, `multi.mbt` and `exchange.py` to a directory outside the MoonJLS checkout. Copy `multiplane.py` as well for the multicomponent workflow below. Build with Python 3.10 or later and MoonBit 0.1.20261119. The Native project imports the exact public dependency `ZSY2221/moon_jpegls@0.9.2`.

~~~sh
moon update
moon build --target native --release --deny-warn
consumer=_build/native/release/build/moonjls_raster_stream.exe
python3 exchange.py encode --consumer "$consumer" \
  --input height-map.pgm --scale -0.25 --offset 12.5 \
  --epsilon 0.74999999999999 --unit count \
  --jls height-map.jls --sidecar height-map.raster.json
python3 exchange.py restore --consumer "$consumer" \
  --jls height-map.jls --sidecar height-map.raster.json \
  --original height-map.pgm \
  --out height-map.u16le --report height-map.restore.json
~~~

For raw input, add `--format raw-u16le --width W --height H --maxval M` and supply the exact raw byte layout. Use `raw-u16be` for big-endian input. Restore derives the original format from the sidecar. With no `--original`, the report records `originalComparison.status` as `not_run`. The producer prints an exact physical error bound and the measured maximum, calculated by the public MoonBit Budget API from the integer error observed across every source row.

The producer stages one canonical copy of the original on disk. It hashes the original container and JPEG-LS incrementally, then decodes its output and compares each reconstructed row before publishing. The recovery host hashes a private staged copy of the input codestream and writes and hashes reconstruction one row at a time. The Native consumer validates the actual frame and scan, every row's length and order, EOI and EOF. The host checks the full byte counts and digests against the sidecar. The working buffers scale with row width and the configured chunk, while temporary disk usage scales with the files.

| Option | Default | Scope |
| --- | ---: | --- |
| `--max-file-bytes` | 512 MiB | Each input or staged file, including canonical output |
| `--max-staging-bytes` | 1 GiB | Total bytes written to the private staging directories |
| `--max-pixels` | 100,000,000 | Image sample count |
| `--max-metadata-bytes` | 1 MiB | Native codec marker payload |
| `--chunk-bytes` | 65,536 | Native and host codestream I/O chunk, up to 1 MiB |
| `--timeout-seconds` | 300 | Per Native subprocess |

Input dimensions are limited to 65,535 on each axis, PGM headers to 64 KiB, and each sidecar or report to 16 KiB. Choose new final paths with existing parent directories on filesystems that support hard links. The sidecar follows the JLS and the recovery report follows the RAW as the completion record. Each file is published by its own no-overwrite operation after validation. A handled error before completion removes files from that attempt, allowing the same command to be retried after fixing the cause.

## Multicomponent exchange

`multiplane.py` handles two to four known-height planes with equal dimensions, H=V=1, a common coded precision and MAXVAL, Pt=0, and identity mapping. It supports independent ILV=0 scans, shared ILV=1 or ILV=2 scans, and valid mixed groups. Originals may use P5 PGM or separately declared U16 byte order. Shared scans use the smallest exact NEAR limit among their members. The v2 sidecar records the actual scan structure and per-ID calibration, original and canonical plane hashes, and error measurements. Units remain attached to each component. Raw recovery concatenates tight U16LE planes in SOF order.

```json
{
  "schema": "moonjls.raster-exchange-request/v2",
  "width": 3, "height": 2, "bits": 16, "maxval": 65535,
  "sofOrder": [11, 4, 19],
  "components": {
    "11": { "name": "Temperature", "path": "c11.u16le", "format": "raw-u16le", "calibration": { "source": "user_declared", "scale": "-0.25", "offset": "100", "epsilon": "0.74999999999999", "unit": "K" } },
    "4": { "name": "Height", "path": "c4.u16be", "format": "raw-u16be", "calibration": { "source": "user_declared", "scale": "0.5", "offset": "0", "epsilon": "1.50", "unit": "m" } },
    "19": { "name": "Count", "path": "c19.u16le", "format": "raw-u16le", "calibration": { "source": "user_declared", "scale": "1.5", "offset": "0", "epsilon": "0", "unit": "count" } }
  },
  "scans": [{ "componentIds": [11, 4], "interleave": 2 }, { "componentIds": [19], "interleave": 0 }]
}
```

Save this request as `planes.json` next to three twelve-byte RAW inputs. Use the published Native CLI (0.9.0 or later) for production. Recovery only needs the independently built consumer and Python scripts.

```sh
python3 multiplane.py encode --cli /path/to/moonjls --consumer "$consumer" \
  --request planes.json --jls planes.jls --sidecar planes.raster.json
python3 multiplane.py restore --consumer "$consumer" \
  --jls planes.jls --sidecar planes.raster.json --out planes.u16le --report planes.restore.json \
  --original 11=c11.u16le --original 4=c4.u16be --original 19=c19.u16le
```

Use the v1 command for single-component v1 sidecars. An omitted original leaves that component's `originalComparison.status` as `not_run`. The decoder checks the actual SOF/SOS, each row's ID and index, strict EOI and EOF, per-plane and whole-output digests, and any provided original. SHA-256 associates file bytes. Calibration authenticity requires an external trusted source.

The host reuses a component's exact MoonBit results within one operation for identical integer errors. In the three small recovery fixtures, this reduced the number of Native budget processes from 15 to 3–5. [Paired measurements](../../reports/multiplane-budget-20261202/README.md)

The producer snapshots each source on disk and verifies every decoded row. SOF-ordered independent scans hash canonical output directly. A candidate whose actual scans all have NEAR=0 may reuse the snapshot's combined canonical digest after exact row equality, per-plane decoded digest checks and strict decoder completion. Other candidates stage their canonical reconstruction, then read it back in SOF order. Recovery always writes the actual RAW file. Working buffers scale with row width, up to four components and the I/O chunk. The sample cap counts all planes together. DNL height resolution, restarts, mapped samples and special NoData are outside this application profile.

## Compare scan candidates

Use a v2 request from the section above. The Native planner reads bounded metadata and returns the default candidates and the request's manual plan if distinct. It can print plans before the plane files are available.

```sh
moonjls plan-raster-scans request.json > plans.json
python3 multiplane.py compare --cli /path/to/moonjls --consumer /path/to/moonjls_raster_stream.exe \
  --request request.json --jls winner.jls --sidecar winner.raster.json \
  --max-staging-bytes 536870912 > comparison.json
```

Comparison freezes the request bytes, stages each source once and validates each candidate by strict decode and full row comparison. It keeps one provisional winner and one active trial in private storage. It chooses the smallest verified JLS, then the fewest scans and canonical ID for ties. The existing two-file transaction publishes the winner JLS and v2 sidecar. Existing restoration accepts those files.

The staging cap counts cumulative successful payload and metadata writes in the staging transaction. It covers the source snapshot, every candidate JLS, any canonical files actually written, the planning request, the candidate configurations and the final sidecar. Deleting scratch never restores the budget. `resourcePreflight` reports a known lower bound after planning and before snapshotting. It leaves compressed sizes, wall time, RSS and peak disk allocation unknown. Runtime limits still apply. `writeLedger` reports the successful writes by category, including on failure. Its units are logical bytes accepted by the writer. An explicit `--journal DIR` keeps the existing Linux/WSL recovery journal on its own path. The comparison prints to stdout and the v2 sidecar remains the completion record. [Native comparison and cold recovery](../../reports/native-resource-proof-20261202/README.md)

## Recover an abruptly terminated task

On Linux or WSL, keep `crash_journal.py` next to `exchange.py` and `multiplane.py` and add `--journal path/to/task` to the existing encode or restore command. Choose a new private journal directory under an existing parent. Use filesystems with hard links, file and directory `fsync`, and advisory locking. Keep the original output directories available during recovery.

```sh
python3 crash_journal.py inspect path/to/task
python3 crash_journal.py recover path/to/task
```

A `discarded` result removes verified task-owned staging from an incomplete job. Retry the original command including the same journal path. It preserves the previous task record. A `complete` result has both verified output files, and recovery can safely run again. Recovery after publishing the first output checks the private stage's identity and digest, then publishes only the missing files. A `conflict` result leaves the replacement or unconfirmed files and reports the reason. Automatic recovery never deletes a public destination. Directory and file synchronization were exercised with process termination. Filesystem and device behavior under power loss remains unverified. [Crash-point verifier and receipt](../../reports/overnight-20261201/G4.md)

## Reproduce the large-file check

The validation driver in this checkout uses the Native consumer built above, the outside project's `moon tree --json` result and the pinned NumPy/CharLS wheels. It measures fixed-width streaming at 2, 8 and 64 MiB of deterministic unsigned U16 source data. A separate complete-image CharLS decode verifies the actual 64 MiB case's codestream and reconstruction hash. [Pinned oracle](../../scripts/oracle-requirements.txt) · [Run and resource receipt](../../reports/host-streaming-20261201/raster-stream.json)

~~~sh
# Run in the outside project first.
moon tree --json > dependency-tree.json

# Run in the checkout with the paths from the outside build.
python3 examples/raster-stream/verify.py \
  --consumer /path/to/moonjls_raster_stream.exe \
  --consumer-source /path/to/independent-project \
  --dependency-tree /path/to/dependency-tree.json \
  --deps /path/to/pinned-oracle-wheels-installed \
  --work-directory /path/to/new-working-directory \
  --output /path/to/new-raster-stream-receipt.json
~~~
