From 2eeed94e513f468ab83c3066eafa58712a346d92 Mon Sep 17 00:00:00 2001 From: denstu473 <63150090+denstu473@users.noreply.github.com> Date: Sun, 18 Oct 2026 21:58:06 +0200 Subject: [PATCH] test(atn): add native parser matrix and contract fixtures --- .github/workflows/atn.yml | 166 ++++++++++++ .github/workflows/ci.yml | 5 +- ATTRIBUTION.md | 6 + crates/psd/fuzz/fuzz_targets/atn.rs | 12 +- crates/psd/tests/atn_contract.rs | 239 ++++++++++++++++++ crates/psd/tests/common/atn_roundtrip.rs | 71 ++++++ crates/psd/tests/fixtures/atn/README.md | 19 ++ crates/psd/tests/fixtures/atn/descriptors.atn | Bin 0 -> 859 bytes crates/psd/tests/fixtures/atn/empty.atn | Bin 0 -> 13 bytes crates/psd/tests/fixtures/atn/float-bits.atn | Bin 0 -> 428 bytes crates/psd/tests/fixtures/atn/metadata.atn | Bin 0 -> 214 bytes docs/atn-testing.md | 97 +++++++ docs/development.md | 3 + 13 files changed, 609 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/atn.yml create mode 100644 crates/psd/tests/atn_contract.rs create mode 100644 crates/psd/tests/common/atn_roundtrip.rs create mode 100644 crates/psd/tests/fixtures/atn/README.md create mode 100644 crates/psd/tests/fixtures/atn/descriptors.atn create mode 100644 crates/psd/tests/fixtures/atn/empty.atn create mode 100644 crates/psd/tests/fixtures/atn/float-bits.atn create mode 100644 crates/psd/tests/fixtures/atn/metadata.atn create mode 100644 docs/atn-testing.md diff --git a/.github/workflows/atn.yml b/.github/workflows/atn.yml new file mode 100644 index 00000000000..1895598e282 --- /dev/null +++ b/.github/workflows/atn.yml @@ -0,0 +1,166 @@ +name: ATN + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + merge_group: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + inputs: + fuzz_seconds: + description: "Seconds of ATN parser fuzzing" + type: choice + options: ["60", "300", "600"] + default: "60" + +permissions: + contents: read + +concurrency: + group: atn-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_RELEASE_DEBUG: "0" + # Keep optimized arithmetic behavior without paying for release LTO in a parser test job. + CARGO_PROFILE_RELEASE_LTO: "false" + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" + +jobs: + parser: + name: ATN parser (${{ matrix.target }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + # These small CPU-only jobs can share the macOS pool with release builds. + max-parallel: 3 + matrix: + include: + - { os: ubuntu-24.04, target: x86_64-unknown-linux-gnu, arch: X64 } + - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu, arch: ARM64 } + - { os: windows-2025, target: x86_64-pc-windows-msvc, arch: X64 } + - { os: windows-11-arm, target: aarch64-pc-windows-msvc, arch: ARM64 } + - { os: macos-15-intel, target: x86_64-apple-darwin, arch: X64 } + - { os: macos-15, target: aarch64-apple-darwin, arch: ARM64 } + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + key: atn-parser-${{ matrix.target }} + save-if: ${{ github.ref == 'refs/heads/main' }} + cache-on-failure: true + - name: Record native execution environment + env: + EXPECTED_ARCH: ${{ matrix.arch }} + TEST_TARGET: ${{ matrix.target }} + run: | + mkdir -p atn-results + # A successful cross-compilation must never stand in for native execution. + test "$RUNNER_ARCH" = "$EXPECTED_ARCH" + { + git rev-parse HEAD + printf 'runner=%s arch=%s target=%s\n' "$RUNNER_OS" "$RUNNER_ARCH" "$TEST_TARGET" + printf 'image=%s version=%s\n' "${ImageOS:-unknown}" "${ImageVersion:-unknown}" + rustc -vV + cargo -V + } | tee atn-results/environment.txt + - name: Parser unit tests + env: + TEST_TARGET: ${{ matrix.target }} + run: | + set -o pipefail + cargo test --locked -p photocraft-psd --target "$TEST_TARGET" --lib atn::tests:: -- --nocapture 2>&1 | tee atn-results/unit.log + - name: Parser contract tests (debug) + env: + TEST_TARGET: ${{ matrix.target }} + run: | + set -o pipefail + cargo test --locked -p photocraft-psd --target "$TEST_TARGET" --test atn_contract -- --nocapture 2>&1 | tee atn-results/debug.log + - name: Parser contract tests (release) + env: + TEST_TARGET: ${{ matrix.target }} + run: | + set -o pipefail + cargo test --locked --release -p photocraft-psd --target "$TEST_TARGET" --test atn_contract -- --nocapture 2>&1 | tee atn-results/release.log + - name: Upload parser evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: atn-parser-${{ matrix.target }} + path: atn-results/ + if-no-files-found: error + retention-days: 14 + + parser-gate: + name: ATN parser gate + needs: parser + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Require every native parser leg + env: + PARSER_RESULT: ${{ needs.parser.result }} + run: test "$PARSER_RESULT" = success + + fuzz: + name: ATN parser fuzz + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@nightly + - uses: Swatinem/rust-cache@v2 + with: + key: atn-fuzz + workspaces: crates/psd/fuzz + save-if: ${{ github.ref == 'refs/heads/main' }} + cache-on-failure: true + - name: Install cargo-fuzz + run: cargo install cargo-fuzz --locked + - name: Seed parser fuzzing with the contract fixtures + run: | + mkdir -p crates/psd/fuzz/corpus/atn atn-results + cp crates/psd/tests/fixtures/atn/*.atn crates/psd/fuzz/corpus/atn/ + { + git rev-parse HEAD + rustc -vV + cargo fuzz --version + sha256sum crates/psd/tests/fixtures/atn/*.atn + } | tee atn-results/fuzz-environment.txt + - name: Fuzz ATN parsing and writing + working-directory: crates/psd + env: + FUZZ_SECONDS: ${{ inputs.fuzz_seconds || '60' }} + run: | + set -o pipefail + cargo fuzz run atn -- -max_total_time="$FUZZ_SECONDS" -max_len=65536 -rss_limit_mb=512 -timeout=5 2>&1 | tee ../../atn-results/fuzz.log + - name: Upload fuzz evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: atn-fuzz-evidence + path: | + atn-results/ + crates/psd/fuzz/artifacts/atn/ + crates/psd/fuzz/corpus/atn/ + if-no-files-found: warn + retention-days: 14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba8243353d2..b92a4aae47b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,7 @@ jobs: # Which OSes the test job runs on. main, manual runs and PRs labelled `full-ci` get Linux and # Windows. Other PRs get Linux, plus Windows when they touch code whose behaviour differs by # platform: the app shell, UI, text and fonts, GPU, pen input, build scripts or the lockfile. - # macOS is tested only by release.yml. + # Full-workspace macOS tests run in release.yml; atn.yml has a small native parser matrix. platforms: timeout-minutes: 10 name: select platforms @@ -56,7 +56,7 @@ jobs: BASE: ${{ github.event.pull_request.base.sha }} FULL: ${{ contains(github.event.pull_request.labels.*.name, 'full-ci') }} run: | - # No macOS on PRs or main: the org's 5 macOS slots are kept for release builds, and + # No full-workspace macOS leg on PRs or main: the org's 5 slots serve release builds, and # release.yml builds and tests macOS (a failing release is fixed and rebuilt). # Windows tests run as two legs in parallel: the unit tests and the integration tests. As # one job they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting @@ -399,6 +399,7 @@ jobs: target: - { crate: psd, name: parse } - { crate: psd, name: descriptor } + - { crate: psd, name: atn } - { crate: psd, name: image_source_data } - { crate: psd, name: grd } - { crate: psd, name: ase } diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index cbbbe069a52..2d2d831fd64 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -118,4 +118,10 @@ next to the files: | `corpus/pngsuite/` | PngSuite | Willem van Schaik | | Public domain | | `corpus/pixls/` (11 files) | Real camera raws, one per decode path: Canon PowerShot SX50 HS (CR2 and its DNG conversion), Nikon D3 uncompressed NEF and Z6 paired 12/14-bit lossy and packed NEFs, Sony DSC-RX0 cRAW ARW, Panasonic DC-G9 high-res RW2, Olympus E-1 GRBG ORF, plus the E-5 packed ORF as the documented known-unsupported case. Per file (each CC0, per its database entry): [IMG_4059.CR2](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/IMG_4059.CR2), [CRW_4061.DNG](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/CRW_4061.DNG), [JD1_8203.NEF](https://raw.pixls.us/data/Nikon/D3/JD1_8203.NEF), [DSC00009.ARW](https://raw.pixls.us/data/Sony/DSC-RX0/DSC00009.ARW), [P1000475.RW2](https://raw.pixls.us/data/Panasonic/DC-G9/P1000475.RW2), [E_1__C106743_gredos.ORF](https://raw.pixls.us/data/Olympus/E-1/E_1__C106743_gredos.ORF), [_7061961_copy.ORF](https://raw.pixls.us/data/Olympus/E-5/_7061961_copy.ORF), [DSC_0750.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0750.NEF), [DSC_0751.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0751.NEF), [DSC_0753.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0753.NEF), [DSC_0754.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0754.NEF) | The photographers of the pixls.us raw samples database | [raw.pixls.us](https://raw.pixls.us) `data/`, fetched per [xtask/src/corpus_pins.rs](xtask/src/corpus_pins.rs) | CC0 / public domain, per file as linked | +## Synthetic parser test fixtures + +| Path | Title | Author | Source | License | +|---|---|---|---|---| +| `crates/psd/tests/fixtures/atn/*.atn` | Independently encoded ATN version-16 parser fixtures | PhotoCraft contributors | Original synthetic test data; wire layout documented in `crates/psd/src/atn.rs`; provenance in the adjacent README | MIT OR Apache-2.0 | + Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0. diff --git a/crates/psd/fuzz/fuzz_targets/atn.rs b/crates/psd/fuzz/fuzz_targets/atn.rs index 3bb1777c8a3..7d719a0b809 100644 --- a/crates/psd/fuzz/fuzz_targets/atn.rs +++ b/crates/psd/fuzz/fuzz_targets/atn.rs @@ -1,14 +1,12 @@ //! Fuzz the `.atn` actions parser: any input must return `Ok` or `Err`, never panic, and -//! anything that parses must survive a write and parse back equal. +//! anything that parses must survive writing, reparsing and stable canonical writing. #![no_main] use libfuzzer_sys::fuzz_target; -use photocraft_psd::atn; + +#[path = "../../tests/common/atn_roundtrip.rs"] +mod atn_roundtrip; fuzz_target!(|data: &[u8]| { - if let Ok(f) = atn::parse(data) { - let bytes = atn::write(&f).expect("a parsed set is writable"); - let again = atn::parse(&bytes).expect("a written set parses"); - assert_eq!(again.actions, f.actions); - } + atn_roundtrip::check(data); }); diff --git a/crates/psd/tests/atn_contract.rs b/crates/psd/tests/atn_contract.rs new file mode 100644 index 00000000000..55d7a6623de --- /dev/null +++ b/crates/psd/tests/atn_contract.rs @@ -0,0 +1,239 @@ +//! Portable public-API contract, executed natively in debug and release by ATN CI. +use photocraft_psd::PsdError; +use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use photocraft_psd::descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value}; + +#[path = "common/atn_roundtrip.rs"] +mod atn_roundtrip; + +const FIXTURES: &[(&str, &[u8])] = &[ + ("empty", include_bytes!("fixtures/atn/empty.atn")), + ("metadata", include_bytes!("fixtures/atn/metadata.atn")), + ("descriptors", include_bytes!("fixtures/atn/descriptors.atn")), + ("float bits", include_bytes!("fixtures/atn/float-bits.atn")), +]; + +fn file_with(desc: Descriptor) -> AtnFile { + AtnFile { + actions: vec![AtnAction { + items: vec![AtnItem { event: AtnEvent::Code(*b"test"), descriptor: Some(desc), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + } +} + +fn class(id: &str) -> Class { + Class { name: UnicodeString::default(), class_id: Id::new(id) } +} + +#[test] +fn independent_wire_fixtures_parse_and_write_byte_exactly() { + for (name, bytes) in FIXTURES { + let parsed = atn::parse(bytes).unwrap(); + assert!(parsed.warnings.is_empty(), "{name}"); + assert_eq!(atn::write(&parsed).unwrap(), *bytes, "{name}"); + atn_roundtrip::check(bytes); + } + assert_eq!(atn::write(&AtnFile::default()).unwrap(), FIXTURES[0].1); + assert_eq!(&FIXTURES[0].1[..4], &[0, 0, 0, 16], "the wire version is big-endian on every host"); +} + +#[test] +fn unicode_metadata_unknown_events_and_dialog_flags_are_preserved() { + let file = atn::parse(FIXTURES[1].1).unwrap(); + assert_eq!(file.name.0, vec![0x0053, 0x0065, 0x0074, 0x0020, 0xd83d, 0xde80, 0xd800, 0]); + assert!(file.expanded); + assert_eq!(file.actions.len(), 2); + let action = &file.actions[0]; + assert_eq!(action.name, UnicodeString::new_nul("Action Ω")); + assert_eq!((action.function_key, action.shift, action.command, action.color, action.expanded), (12, true, true, 7, true)); + let blur = &action.items[0]; + assert_eq!((blur.expanded, blur.enabled, blur.with_dialog, blur.dialog_options), (true, true, true, 2)); + assert_eq!(blur.event, AtnEvent::Code(*b"GsnB")); + assert_eq!(blur.descriptor, Some(Descriptor::new("null").with("Rds ", Value::UnitFloat { unit: *b"#Pxl", value: 2.5 }))); + let future = &action.items[1]; + assert_eq!(future.event, AtnEvent::Name("syntheticFutureEvent".into())); + assert_eq!((future.expanded, future.enabled, future.with_dialog, future.dialog_options), (false, false, true, 255)); + assert_eq!(future.dictionary, "Future event"); + assert!(future.descriptor.is_none()); + assert_eq!(file.actions[1].name, UnicodeString::new_nul("Empty")); + assert!(file.actions[1].items.is_empty()); +} + +#[test] +fn every_descriptor_variant_and_reference_form_is_retained() { + let expected = Descriptor::new("syntheticRoot") + .with( + "reference", + Value::Reference(vec![ + ReferenceItem::Property { class: class("Lyr "), key: Id::new("Nm ") }, + ReferenceItem::Class(class("Dcmn")), + ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }, + ReferenceItem::Offset { class: class("Lyr "), offset: -3 }, + ReferenceItem::Identifier { class: class("Lyr "), id: 0x1234_5678 }, + ReferenceItem::Index { class: class("Lyr "), index: 4 }, + ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul("Layer Ω") }, + ]), + ) + .with("nested", Value::Descriptor(Descriptor::new("child").with("flag", Value::Boolean(true)))) + .with("global", Value::GlobalObject(Descriptor::new("global"))) + .with("list", Value::List(vec![Value::Boolean(false), Value::Double(-3.5), Value::Text(UnicodeString::new("Ω"))])) + .with("double", Value::Double(1.25)) + .with("unit", Value::UnitFloat { unit: *b"#Prc", value: 37.5 }) + .with("units", Value::UnitFloats { unit: *b"#Pxl", values: vec![1.25, -0.0, -2.5] }) + .with("text", Value::Text(UnicodeString(vec![0x0054, 0x0065, 0x0078, 0x0074, 0x0020, 0xd83d, 0xde80, 0xdfff, 0]))) + .with("enum", Value::Enumerated { type_id: Id::new("Ordn"), value: Id::new("syntheticValue") }) + .with("integer", Value::Integer(i32::MIN)) + .with("large", Value::LargeInteger(0x0123_4567_89ab_cdef)) + .with("boolean", Value::Boolean(true)) + .with("class", Value::Class(class("Lyr "))) + .with("globalClass", Value::GlobalClass(class("Dcmn"))) + .with("alias", Value::Alias(vec![0, 255, 1, 128])) + .with("path", Value::Path(b"C:\\synthetic\\image.psd\0".to_vec())) + .with("raw", Value::RawData(vec![0, 127, 128, 255])) + .with( + "objectArray", + Value::ObjectArray(ObjectArray { + prefix: 16, + body: Descriptor::new("rationalPoint").with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: vec![1.0, 2.0] }), + }), + ); + let file = atn::parse(FIXTURES[2].1).unwrap(); + assert_eq!(file.actions[0].items[0].descriptor, Some(expected)); +} + +#[test] +fn nan_payloads_signed_zero_and_infinities_survive_without_false_fuzz_failures() { + let file = atn::parse(FIXTURES[3].1).unwrap(); + let descriptor = file.actions[0].items[0].descriptor.as_ref().unwrap(); + for (key, bits) in [ + ("nan", 0x7ff8_0000_0000_1234), + ("negativeZero", 0x8000_0000_0000_0000), + ("positiveInfinity", 0x7ff0_0000_0000_0000), + ("negativeInfinity", 0xfff0_0000_0000_0000), + ] { + let Some(Value::Double(value)) = descriptor.get(key) else { panic!("missing {key}") }; + assert_eq!(value.to_bits(), bits, "{key}"); + } + // Ordinary AST PartialEq fails for NaN, despite this valid byte-exact round trip. + assert_ne!(file.actions.clone(), file.actions); + atn_roundtrip::check(FIXTURES[3].1); +} + +#[test] +fn every_truncated_fixture_is_refused() { + for (name, bytes) in FIXTURES { + for end in 0..bytes.len() { + assert!(atn::parse(&bytes[..end]).is_err(), "{name}: cut at {end}/{}", bytes.len()); + } + } +} + +#[test] +fn trailing_bytes_only_add_a_diagnostic() { + for (name, bytes) in FIXTURES { + let mut input = bytes.to_vec(); + input.extend_from_slice(b"extra"); + let mut parsed = atn::parse(&input).unwrap(); + assert_eq!(parsed.warnings, ["5 trailing bytes ignored"], "{name}"); + parsed.warnings.clear(); + assert_eq!(atn::write(&parsed).unwrap(), *bytes, "{name}"); + atn_roundtrip::check(&input); + } +} + +#[test] +fn unsupported_versions_and_invalid_item_tags_are_refused() { + for version in [0_u32, 12, 15, 17, u32::MAX] { + let mut input = FIXTURES[0].1.to_vec(); + input[..4].copy_from_slice(&version.to_be_bytes()); + assert!(matches!(atn::parse(&input), Err(PsdError::Unsupported(_)))); + } + let file = file_with(Descriptor::new("null")); + let valid = atn::write(&file).unwrap(); + // The empty set/action names put the first step at offset 28. + for kind in [*b"bad!", *b"LONG", [0; 4]] { + let mut input = valid.clone(); + input[32..36].copy_from_slice(&kind); + assert!(matches!(atn::parse(&input), Err(PsdError::Invalid(_)))); + } + for flag in [-2_i32, 1, i32::MAX] { + let mut input = valid.clone(); + input[44..48].copy_from_slice(&flag.to_be_bytes()); + assert!(matches!(atn::parse(&input), Err(PsdError::Invalid(_)))); + } +} + +#[test] +fn declared_action_and_step_limits_are_enforced() { + let mut actions = FIXTURES[0].1.to_vec(); + let count = (atn::MAX_ACTIONS + 1) as u32; + actions[9..13].copy_from_slice(&count.to_be_bytes()); + actions.resize(13 + count as usize * 15, 0); + assert!(matches!(atn::parse(&actions), Err(PsdError::LimitExceeded("too many actions in one set")))); + + let mut steps = atn::write(&AtnFile { actions: vec![AtnAction::default()], ..Default::default() }).unwrap(); + let count = (atn::MAX_ITEMS + 1) as u32; + steps[24..28].copy_from_slice(&count.to_be_bytes()); + steps.resize(28 + count as usize * 20, 0); + assert!(matches!(atn::parse(&steps), Err(PsdError::LimitExceeded("too many steps in one action")))); + + let mut short = FIXTURES[0].1.to_vec(); + short[9..13].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(matches!(atn::parse(&short), Err(PsdError::UnexpectedEof { .. }))); +} + +#[test] +fn nested_descriptors_obey_the_parser_depth_limit() { + let mut desc = Descriptor::new("leaf").with("flag", Value::Boolean(true)); + for _ in 0..2 { + desc = Descriptor::new("node").with("next", Value::Descriptor(desc)); + } + let shallow = atn::write(&file_with(desc.clone())).unwrap(); + atn_roundtrip::check(&shallow); + assert!(atn::parse(&shallow).is_ok()); + for _ in 0..MAX_DEPTH + 2 { + desc = Descriptor::new("node").with("next", Value::Descriptor(desc)); + } + let deep = atn::write(&file_with(desc)).unwrap(); + assert!(matches!(atn::parse(&deep), Err(PsdError::LimitExceeded(_)))); +} + +#[test] +fn generated_metadata_and_float_patterns_round_trip() { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + for index in 0..256_u16 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let mut file = file_with(Descriptor::new("generated").with("value", Value::Double(f64::from_bits(seed)))); + file.name = UnicodeString(vec![index, 0xd800 | index, 0, 0xffff]); + file.expanded = index & 1 != 0; + let action = &mut file.actions[0]; + action.function_key = index; + action.shift = index & 2 != 0; + action.command = index & 4 != 0; + action.color = index; + action.expanded = index & 8 != 0; + action.name = UnicodeString(vec![0xdc00 | index, index]); + let item = &mut action.items[0]; + item.expanded = index & 16 != 0; + item.enabled = index & 32 != 0; + item.with_dialog = index & 64 != 0; + item.dialog_options = index as u8; + atn_roundtrip::check(&atn::write(&file).unwrap()); + } +} + +#[test] +fn actual_fuzz_invariant_handles_deterministic_seed_mutations() { + for (_, bytes) in FIXTURES { + for index in 0..128 { + let mut mutated = bytes.to_vec(); + let at = index * 47 % mutated.len(); + mutated[at] ^= (index as u8).wrapping_mul(13).wrapping_add(1); + atn_roundtrip::check(&mutated); + } + } +} diff --git a/crates/psd/tests/common/atn_roundtrip.rs b/crates/psd/tests/common/atn_roundtrip.rs new file mode 100644 index 00000000000..8b71754b561 --- /dev/null +++ b/crates/psd/tests/common/atn_roundtrip.rs @@ -0,0 +1,71 @@ +//! Shared invariant for the parser contract suite and the actual cargo-fuzz target. +use photocraft_psd::atn::{self, AtnFile}; +use photocraft_psd::descriptor::{Descriptor, Value}; + +fn scalar(value: &mut f64, bits: &mut Vec) { + bits.push(value.to_bits()); + // AST equality must remain meaningful when a valid descriptor contains NaN. + if value.is_nan() { + *value = 0.0; + } +} + +fn descriptor(desc: &mut Descriptor, bits: &mut Vec) { + for (_, item) in &mut desc.items { + value(item, bits); + } +} + +fn value(item: &mut Value, bits: &mut Vec) { + match item { + Value::Double(v) | Value::UnitFloat { value: v, .. } => scalar(v, bits), + Value::UnitFloats { values, .. } => { + for v in values { + scalar(v, bits); + } + } + Value::Descriptor(d) | Value::GlobalObject(d) => descriptor(d, bits), + Value::ObjectArray(array) => descriptor(&mut array.body, bits), + Value::List(items) => { + for item in items { + value(item, bits); + } + } + Value::Reference(_) + | Value::Text(_) + | Value::Enumerated { .. } + | Value::Integer(_) + | Value::LargeInteger(_) + | Value::Boolean(_) + | Value::Class(_) + | Value::GlobalClass(_) + | Value::Alias(_) + | Value::Path(_) + | Value::RawData(_) => {} + } +} + +fn floats(file: &mut AtnFile) -> Vec { + let mut bits = Vec::new(); + for action in &mut file.actions { + for item in &mut action.items { + if let Some(d) = &mut item.descriptor { + descriptor(d, &mut bits); + } + } + } + bits +} + +pub fn check(data: &[u8]) { + if let Ok(mut original) = atn::parse(data) { + let encoded = atn::write(&original).expect("a parsed set is writable"); + let mut again = atn::parse(&encoded).expect("a written set parses"); + assert_eq!(atn::write(&again).expect("a reparsed set is writable"), encoded); + assert_eq!(floats(&mut original), floats(&mut again), "every floating-point bit pattern survives"); + // Trailing-input diagnostics are not serialized into an action set. + original.warnings.clear(); + again.warnings.clear(); + assert_eq!(again, original, "set metadata, action metadata and every descriptor value survive"); + } +} diff --git a/crates/psd/tests/fixtures/atn/README.md b/crates/psd/tests/fixtures/atn/README.md new file mode 100644 index 00000000000..e26382f1ea3 --- /dev/null +++ b/crates/psd/tests/fixtures/atn/README.md @@ -0,0 +1,19 @@ +# Synthetic ATN parser fixtures + +These four tiny files were independently encoded field by field from the version-16 layout +documented in `src/atn.rs`, without calling PhotoCraft's writer. They are original test data, +licensed MIT OR Apache-2.0 under the repository's licenses. They contain no user artwork, +Photoshop program code or proprietary assets. They are not Photoshop-authored interoperability +oracles. + +| File | Bytes | Purpose | SHA-256 | +|---|---:|---|---| +| `empty.atn` | 13 | Empty set and explicit big-endian version | `6fd936f91296a13b0e7456a38b139a100fd17407d1c582d4502ce76413d01539` | +| `metadata.atn` | 214 | UTF-16 surrogate pairs/unpaired units, action order, function key, modifiers, panel flags, disabled step, unknown string event, dialog options | `cec2ff5a25e003aa29e790ea6b110f06ba848f0afd7901f3f8ad4740f782ede2` | +| `descriptors.atn` | 859 | Every descriptor value variant and every reference form currently represented by the parser | `6c76502822c1f36c8060a71adb227c4540663518785bbab1b70951dac0ef58ad` | +| `float-bits.atn` | 428 | NaN payload, negative zero, infinities, and floats inside lists, objects and arrays | `0aa6278a569c777f249b305e889896132c2a87e44a24cb1a55d1d3fc0928fd0c` | + +`tests/atn_contract.rs` checks the independently encoded bytes and expected public structures. +The ATN fuzz job copies the same files into its seed corpus. A fixture change should explain +the changed wire fields and update this table; do not regenerate expectations merely to make a +failing parser pass. diff --git a/crates/psd/tests/fixtures/atn/descriptors.atn b/crates/psd/tests/fixtures/atn/descriptors.atn new file mode 100644 index 0000000000000000000000000000000000000000..26b1bdd361babd5886fa5b910a41cbba94245c67 GIT binary patch literal 859 zcmY*Y!EVz)5FHacp(;gHFL1P!J10&^s4Zy99@x~p-oLu zIcz1DtjW1s60ABD28 zZYD?EV~2|%(~D&NXhVDHgXY6sW+bvb{_V?YTd2ZaDtF$WnDpe;x+NmU?WH=G{mD`i z+G&ewpRx|yTmXkl=RdXwQ|fjJ4&rYwzt=zf98oPwez?Z#{dhasnUD)su2(3BIU1=| zUUMcuB!$T_)nyg*hxw;3Uw;zV<4#eiR;4JF!dkvLO$`}8+Wn1u1ExvCK}+*ZAU_ha z5S9$f7s7o|b3!HDeB$OYxlaZ!uC}MVDoT;#v&!!h&&e*xYb#x(!{ literal 0 HcmV?d00001 diff --git a/crates/psd/tests/fixtures/atn/empty.atn b/crates/psd/tests/fixtures/atn/empty.atn new file mode 100644 index 0000000000000000000000000000000000000000..dbcd73d1960acb305ebb3f59856a5b13e1c1f265 GIT binary patch literal 13 NcmZQzU=Uz{0RRB401*HH literal 0 HcmV?d00001 diff --git a/crates/psd/tests/fixtures/atn/float-bits.atn b/crates/psd/tests/fixtures/atn/float-bits.atn new file mode 100644 index 0000000000000000000000000000000000000000..0f272adea8052e66dc94016aba18757b1d53925e GIT binary patch literal 428 zcmY*W%}&EG3{HnSegsm*6Cmvsc!6;!AR)Dvap0D;S(nMOQIbx;g*`GyZo}>xD3nqh;xGJTt`r5O&dq$k0Uzq~ncoF&x;&;PbVhcMLLc#_I$%w$z)?Z;80R zQ`(uJ1}r=GYo(w zfEkWZu#nB>^J>@-JRW=@Fl9E!4jIP [out dir]` fills