Skip to content

Harden denoise, merge and camera-profile code against hostile and damaged input - #1935

Merged
emmertex merged 18 commits into
emmertex:stagingfrom
blwfish:fix/merge-camprof-denoise
Dec 5, 2026
Merged

emmertex merged 18 commits into
emmertex:stagingfrom
blwfish:fix/merge-camprof-denoise

Conversation

@blwfish

@blwfish blwfish commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

What

Hardening of three crates from the 2026-12-04 whole-file review (crates/denoise-core + crates/denoise, crates/merge, crates/camprof). Findings only reachable by a hostile or damaged input, or where a result was silently wrong, were fixed; style-only Lows, unmeasured performance rewrites and cross-crate duplicates were not. Release notes: docs/whats-new/2026-12-05-denoise-hardening.md and 2026-12-05-merge-camprof-hardening.md (+ changelog entries).

Per-finding dispositions: denoise 73 fixed / 15 deferred / 23 skipped; merge+camprof 66 fixed / 1 deferred / 87 skipped (several "fixed" are partial, each outcome line says what was left).

Denoise (6 commits DENOISE-HARDEN)

  • Model archive is streamed into a staged file and checked as it unpacks: lying sizes, duplicate entries, multi-disk and trailing bytes are refused.
  • Manifests: the documented key maxDeviation now works (installed copies written earlier still read); unknown keys are reported by name; invisible/bidi characters in names and licence texts are refused.
  • One parameter check shared by raw and finished-picture runs; a nominal scale is removed from finished-picture answers as for raw models.
  • Product cache: synced staged writes, verify(), reserved bytes.
  • Remote tiles carry an optional power-of-two scale (absent = 1) so the default raw model's answer is no longer clipped at the half-float maximum; half-float infinity/NaN in a reply is refused and that tile runs locally.

Merge / camprof (11 commits MERGE-HARDEN, CAMPROF-HARDEN)

  • HDR merge refuses zero-size, more than 32 frames and damaged exposure data (NaN, 60 EV span); mixed portrait/landscape brackets are turned upright before the size check.
  • Pixel shift: a dead frame falls back to the plain merge (reuses FallbackReason::NoStart, which the engine reports as "noMatch"); registered pixel shift checks CFA layout and black/white levels as the plain merge does; clipped samples stay ungained; empty tiles no longer count as a match.
  • Reconstruction: dense hole bitmap, saturating tile bounds. Measured that MARGIN = 8 is sufficient (tiled vs untiled agree to 0.005 DN rms), so no seam fix was made.
  • Camprof: simplex shrink re-evaluates every moved vertex, NaN/sentinel handling; singularity bounds relative to matrix scale; panic-free DynMatrix; chart tests assert their outcome instead of discarding it.

Things to look at

  • Wire format: the remote denoise payload gains an optional scale. Old peers interoperate (absent = 1), but an old client reading a new server's answer would not apply it. Needs Andrew's view if remote denoise is used across versions.
  • Manifests: unknown keys are now reported (was: skipped). A manifest in the wild with an extra key would now be refused; I have not seen any.
  • Behaviour: MIN_TRACKS in the pixel-shift gate 4 → 5 (not reachable today, registration needs 8 tiles).
  • API inside these crates (no callers elsewhere, grepped): DynMatrix::at_mut removed, tiles::MIN_LEVEL/CLIP_FRACTION and positions::MIN_TILES renamed, TileGainReport gained a field.
  • Left alone: crates/camprof matopt has no callers outside its own tests (24 findings skipped; deleting it is the owner's call). Four call sites still fall back to the identity for a genuinely singular user matrix (white_balance_of, render_matrix_only, color_matrix_for, the DCP build) because that needs public signatures used by engine. Engine-side denoise items need Andrew and are deferred.

Verification

  • cargo test -p lcc-merge -p lcc-camprof, cargo clippy ... --all-targets -- -D warnings, cargo fmt --all -- --check pass; cargo check of merge, camprof, denoise-core, denoise and engine passes after merging the latest origin/staging.
  • New tests were checked against the old code for the hdr (5 of 11 fail on old code), simplex, recon and ransac changes; the gain, gate, samples, response, linalg, hostile and iteration_cap tests were not reverted-checked.
  • cargo xtask ci --quick did not pass cleanly on this branch: the test step failed on tests_osd::no_command_that_the_overlay_reports_also_toasts_when_run_with_no_parameters (merge/camprof run) and on two ui-egui tests (denoise run). Each passes when run alone; I have not run them on a clean origin/staging. Not re-run after the final staging merge. deny, wasm, android not run.
  • No speed claims.

Manual: develop/merge.md (HDR orientation mixing, 32-photo and 60 EV refusals, pixel-shift dead-frame fallback); denoise: docs/denoise.md.

🤖 Generated with Claude Code

blwfish and others added 18 commits December 4, 2026 20:43
…e hostile zips

extract() inflates a buffer at a time into a temporary file (crate::staging:
appended .tmp name, remove then create_new, fsync before rename), so a
destination already ending in .part is no longer its own staging file and a
planted link is not written through. The only size limit is the caller's
max_bytes (no 256 MiB literals under the manifest's 2 GiB), the claimed length
is checked against the real file before anything is read, and the end record
must end the file, multi-disk, zip64 local offsets, duplicate names and a count
that hides entries are refused. CRC-32 is crc32fast.

Manual: none, no user-visible change in the manual

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…viation, refuse deceptive text

deny_unknown_fields on the manifest, licence and gain, so a misspelled sha256
or licence is an error instead of a silently applied default. Gain's field is
maxDeviation as docs/denoise.md says (max_deviation is still read). Display
strings refuse bidirectional, zero-width and separator characters, and a line
break outside the notice and provenance. Gain::check and tiles::overlap_fits
are the shared rules a run will use too. Tests pin each limit at, below and
above, and parse the documented JSON by hand.

Manual: none, no user-visible change in the manual

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…, nominal taken out of RGB answers

check_params/check_size replace the hand-copied tile, overlap, gain, clip and
pixel-count checks of denoise_bayer and tiled_rgb (the latter had no gain or
clip check), reusing the manifest's Gain::check and tiles::overlap_fits.
tiled_rgb now divides a MatchMean model's answer by nominal, as the raw path
does. Tests: every manifest-valid geometry and gain is accepted by a run,
hostile parameters never reach the model, the pixel cap is inclusive in both
paths, dark-tile and clip thresholds are pinned.

Manual: none, no user-visible change in the manual

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ed bytes, half crate

write() goes through the shared staging (appended name, synced before the
rename), refuses a key whose header the reader would refuse and reports why a
picture is refused. verify() reads every strip's checksum (is_current stays the
cheap header-and-length check and its doc says so); reserved header bytes and
unknown header keys are refused. CRC is crc32fast and the half-float
converters use the half crate, shown bit-identical to the old ones over every
pattern; the infinity/NaN policy is documented and f16_is_finite exposes it.
Tests replace one that passed without the pixel cap, and pin the header guards,
clip equality, reduced edge blocks and the amount and factor clamps.

Manual: none, no user-visible change in the manual

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…nity and NaN

A model's answer is in its own scale (a million times the picture's for the
default raw model) and a half float stops at 65504, so bright samples of a
tile from a remote server came back flattened. A payload now carries an
optional power-of-two scale (absent = 1, so old peers interoperate), and
unpack refuses the half-float patterns of infinity and NaN instead of reading
them as 65504 (which made the client's finite check unable to fail).

Manual: none, no user-visible change in the manual

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
docs/denoise.md: manifest keys and unknown-key rule, what installation really
checks, the remote payload scale. Release notes for the hardening.

Manual: none, no user-visible change in the manual

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…sentinel and empty-start handling

The shrink step moved all vertices but re-evaluated two, so for n > 2 later ordering, the
centroid and the stop test read stale values (live in the n = 6 forward-matrix fit). A NaN or
infinite objective is now the worst value, the stop test no longer overflows on the f64::MAX
sentinel, an empty start returns at once, and the module docs match the relative stop rule.

Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… panic-free DynMatrix

Mat3::inverted and solve_linear judged singularity against an absolute 1e-14, so a well
conditioned matrix of small entries was refused (and inverted_or_identity silently returned the
identity at ~14 call sites); solve_linear returned Some(NaN) for NaN input. Both now compare
against the matrix's own scale and refuse non-finite input and answers. DynMatrix checks its
size (try_zeros, from_fn) and its indexes (get/set/at never wrap or panic); the correction-table
solve builds its matrix with from_fn.

Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…iscarding it

Every case now asserts no chart found, an error, or a finite and writable profile; an Ok result
with a NaN matrix can no longer pass.

Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…sure brackets; alignment model names in one place

merge_hdr panicked on zero-size frames (par_chunks_mut(0)), took any frame count and size, let an
EXIF exposure difference past ~128 EV overflow exp() into NaN pixels, compared sizes before
turning mixed portrait and landscape frames upright, and branched on the string "identity" typed
at four sites. Now: cap of 32 frames and 2^29 pixels, a fallible output allocation, non-finite
exposures count as missing, a 60 EV span limit, orientation before the size check, align::model_name
constants and Alignment::is_identity, one median_luma rule for float and half-float pixels,
reference_detail reads the half-float pixels instead of a full Rgb32f plus a Frame clone.

Manual: develop/merge.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…t bracket

The round-robin pick k*7 % len repeated one pixel seven times for a bin of 7 and only two for 14
(any length divisible by 7); the stride is now the first prime from 7 that does not divide the
length, a permutation. A bracket whose sampled codes number fewer than 16 (a flat picture) gave
a regularised guess of a curve and now gives none.

Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…owance on tiny consensus; failure-path tests

Translation and Similarity fits returned NaN/inf homographies for non-finite points; the adaptive
iteration count collapsed to 16 draws when (inliers/n)^k rounded p_fail to 1.0. Tests now cover
None below min_inliers (at and above the boundary), unrelated points, empty and coincident input,
NaN/inf, determinism and the strict inlier threshold.

Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e gain skips empty tiles; constants named apart

Per-frame gains had no positivity check: a black or dropped frame gave a gain <= 0 and every
division by it put inf/NaN into the reconstruction. Gains outside 0.5..2 or non-finite are now no
estimate, and the registration refuses such a series (reason noMatch, plain merge). A tile whose
window held no sample of a colour read as level 0 and is now skipped (and counted apart from
clipped ones). The same-named CLIP_FRACTION/MIN_LEVEL/MIN_TILES of tiles, gain and positions have
distinct documented names, with a compile-time check that tile selection is stricter than the gain
estimate. Tests at the boundaries of MIN_TILES (7/8/9) and MAX_DROPPED, at the gain limits, and
for dead, empty and clipped tiles.

Manual: develop/merge.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e levels as the plain merge does

Mosaics::push checked size, active area and sample count only, so a frame of another Bayer layout
was read with the first frame's colour table. It now rejects a different colour filter layout,
black or white level, sample type or samples-per-pixel, with tests for new() and push().

Manual: develop/merge.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ds, clipped samples ungained; gate ignores empty tiles

The hole set was a HashSet with an entry per unreached channel value (unbounded on degenerate
registrations); it is a bitmap now, with a test that it fills exactly as the set did. The tile
bounds did unchecked i64 +-1 after a saturating float cast and now saturate (debug overflow panic on
huge displacements); non-finite displacements are skipped. A clipped sample (>= white) keeps its value
under a gain, as in the plain merge. The gate no longer lets a held-out tile with nothing to predict
vote as a perfect tie, MIN_TRACKS is 5 (four left the model one row and its fit always failed), the
placement box centre derives from BOX, the verdict rule and holdout count are tested at their
boundaries, cubic_at is one shared function, and a tile-offset invariance test shows the 8-node
work-box margin is enough (rms 0.005 DN against 3.7 DN at margin 1).

Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…le hardening

Manual: develop/merge.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Manual: none

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@emmertex

emmertex commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks, merging. A few non-blocking follow-ups noticed in review:

  • crates/denoise-core/src/product.rs verify() isn't called outside tests, but the What's New entry presents it to users; wire it up or drop that line.
  • The remote tile protocol gains scale without bumping PROTOCOL, so an old client against a new server silently gets samples divided by 2^k.
  • A crash mid-extraction can leave model.onnx.part.tmp, which InstallCleanup (crates/engine/src/cmd/denoise.rs) doesn't list, so its remove_dir would fail.
  • Pixel-shift registration reports a dead frame as FallbackReason::NoStart; its own reason would give a clearer message.

@emmertex
emmertex merged commit a0346ca into emmertex:staging Dec 5, 2026
3 checks passed
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