Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

fix(sdk): Asset evidence computation reproducibility fix - #3958

Merged
Sawchord merged 8 commits into
masterfrom
leon/asset_repro_fix
Oct 22, 2024
Merged

Sawchord merged 8 commits into
masterfrom
leon/asset_repro_fix

Conversation

@Sawchord

@Sawchord Sawchord commented Oct 22, 2024 •

Copy link
Copy Markdown
Contributor

Description

This PR fixes an issue with non-reproducibility with regards to asset uploading.
When using zlib-ng backend of flate2, we have the problem that the gzip archives generated on x86 and ARM are not the same.
Since we hash those archives into the evidence when doing an asset upload, this creates a different evidence string when running from x86 vs. ARM.

This PR removes the zlib-ng feature from flate2 altogether. The speedup provided by zlib-ng is not noticeable given that our assets are on the order of megabytes.

How Has This Been Tested?

This branch has been used inside dfx-orbit for a while now, and it fixed the issue.

Checklist:

@Sawchord
Sawchord requested a review from a team as a code owner October 22, 2024 13:38
@Sawchord
Sawchord marked this pull request as draft October 22, 2024 13:42
@Sawchord
Sawchord marked this pull request as ready for review October 22, 2024 14:44
@Sawchord
Sawchord enabled auto-merge (squash) October 22, 2024 15:15
@Sawchord
Sawchord merged commit d65717b into master Oct 22, 2024
@Sawchord
Sawchord deleted the leon/asset_repro_fix branch October 22, 2024 16:03
rikonor pushed a commit that referenced this pull request Feb 3, 2025
* Use different gzip backend

* Reintroduce `zlib-ng` in build-dependencies
cameronraysmith pushed a commit to cameronraysmith/ic that referenced this pull request Nov 20, 2026
…xide 0.9.1 (dfinity#12191)

Updates flate2 from 1.1.9 (Cargo) and 1.1.5 (Bazel) to 1.1.11 in both
builds. Since 1.1.10, flate2's default backend is miniz_oxide 0.9
instead of 0.8, and the locks resolve it to miniz_oxide 0.9.1.

dfinity#12180 held flate2 back for this reason:
- miniz_oxide 0.9.1 rejects some deflate streams that 0.8.9 accepted.
- The replica decodes a canister's stored gzipped Wasm module again
whenever it compiles it, so an installed module could stop loading after
a replica upgrade.

This description sets out how far that risk goes. Whether to take it is
for the Execution team to decide (@dfinity/core-protocol, which owns
`rs/embedders`).

**Recommendation: take it.** A hit is very unlikely (see below). If one
happens, it is limited to that canister, it shows in the replica's
metrics, and a replica release that restores the old rule undoes it.

# What changes for gzipped canister modules

**One stream shape is newly rejected.**
- **The shape:** a dynamic Huffman block whose literal/length or
distance code gives a code to exactly one symbol, with a code length of
2 to 15.
- miniz_oxide 0.9.1 rejects the table as soon as it reads the block
header, even if the block never uses that code (Frommi/miniz_oxide#190,
which fixes Frommi/miniz_oxide#137). 0.8.9 accepted it.
- For the literal/length code this can only be an empty block whose one
code is end-of-block.
- **zlib already rejects it,** and so do GNU gzip and pigz. 0.9.1's
table checks follow zlib's `inflate_table` rule for rule.
- **No other acceptance change:** the 0.8.9 → 0.9.1 inflate diff changes
only this table check.
- In 11 million differential cases, every stream that 0.8.9 accepted and
0.9.1 rejected had this shape. 0.9.1 accepted nothing that 0.8.9
rejected, and streams both accepted decoded to the same bytes.
- Nothing else on the `decode_wasm` path changes which modules are
accepted.

**No common compressor produces that shape:**
- **At least two codes:**
- zlib and its derivatives (zlib-ng, zlib-rs, pako, Node), GNU gzip,
pigz, 7-Zip and ISA-L always emit at least two codes.
- So does libdeflate from 1.19. Earlier versions emit an empty code or
two 1-bit codes, which both versions accept.
- **A 1-bit code:** miniz, miniz_oxide, zopfli, libflate and Go's
compress/flate give a lone symbol a 1-bit code, which both versions
accept.
- **dfx** compresses with flate2 when `"gzip": true` is set and whenever
it rewrites a gzipped module. It has used miniz_oxide since 0.24.2
(dfinity/sdk#3958), and zlib-ng before that.
- **IC tooling:**
- Our canisters are gzipped with pigz. The bundled ic-btc-canister
release uses GNU gzip.
- The asset canister and Internet Identity use `gzip --best --no-name`.
  - icp-cli's recipes use `gzip --no-name`.
- **Experiments:** none of the encoders that could be run here produced
such a table. They were GNU gzip, pigz, busybox, 7-Zip, zlib via Python,
Node and Java, zlib-rs, libdeflate, zopfli, libflate, the deflate crate,
and miniz_oxide 0.8.9 and 0.9.1, directly and through flate2. The runs
covered:
  - 35,522 gzip streams from 57 edge-case and real inputs;
- 948,000 raw streams from 6,000 random inputs, using the Rust encoders.

  Go, ISA-L, pako and zlib-ng were checked in source only.

**None of the real modules we could obtain has it.** All 2,290 distinct
canister modules we found decode to identical bytes with flate2 1.1.5,
1.1.9 and 1.1.11. None of their 79,097 dynamic blocks has an incomplete
or single-symbol table. The modules came from:
- the history of `mainnet-canister-revisions.json` since 2024-10 (581
module hashes);
- DFINITY's CDN for 23 IC versions since 2023-01 (1,043 release
canisters);
- the asset canister and wallet bundled with dfx since 2022-08;
- 22 public IC projects' GitHub releases (529 assets);
- our current canisters, and the modules our Bazel build downloads as
test data.

**Most installed modules are not among them.** A sample of 3,000 mainnet
canisters from the public dashboard API had 843 with a module. Only 252
of those run one of the modules above, and 241 of the 252 are asset
canisters. Checking the rest needs the installed modules themselves.
Someone with access to a recent checkpoint could scan the canisters' and
snapshots' `software.wasm` files for the shape; this is the check dfinity#12180
asked for.

**If an installed module has the shape,** for example because it was
hand-crafted or fuzzed:
- **Its developer would not have noticed.** Today's decoder, miniz_oxide
0.8.9 (on mainnet since dfinity#11669 in October 2026), accepts it. So did
libflate, which the replica used before, and so do dfx, ic-wasm and
7-Zip.
- **After the replica upgrade:**
- Every message to the canister fails with IC0505
(`CanisterInvalidWasm`) on every node, and so do heartbeats and timers.
- The failure is deterministic, so there's no divergence between nodes
and no effect on the rest of the subnet.
- The canister still pays the fixed execution fee for each failed call,
callback and heartbeat. A canister that exports `canister_heartbeat`
pays it every round until it freezes, and a global timer that fires is
used up.
- **A normal upgrade fails too** if the module exports
`canister_pre_upgrade`, because the upgrade runs that hook from the old
module. The options:
- **Upgrade with `skip_pre_upgrade`:** this works and keeps stable
memory. It loses whatever `canister_pre_upgrade` would have saved, which
for canisters that serialize their heap in that hook is all heap state.
With enhanced orthogonal persistence, adding `wasm_memory_persistence =
keep` loses nothing.
- **Reinstall:** this also works, but wipes all state, stable memory
included.
- **Load a snapshot:** this should work without losing state, but is
untested. Take a snapshot, which doesn't decode the module. Download it,
replace its module with the same Wasm gzipped by a standard tool, upload
that as a new snapshot and load it.
- **No controller:** a canister without one can only be fixed by a
replica change.
- **Detection:** the replica counter
`sandboxed_execution_replica_cache_lookups` with `lookup_result`
`embedder_cache_hit_compilation_error` or
`compilation_cache_hit_compilation_error` counts executions that hit a
cached compilation error. A broken canister would make it rise after the
rollout.
- **Reversal:** nothing derived from the failed decode is persisted. The
module and the canister's memory stay as they are, and compilation
results, errors included, are only cached in memory and in a temporary
directory that is wiped when the replica starts. So a replica release
that restores the old rule makes the canister work again. Only the
effects of the failed messages remain: rejects, fees and used-up timers.

**Alternatives, if execution wants no change in what is accepted:**
- **Stay on flate2 1.1.9 / 1.1.5** (miniz_oxide 0.8.9).
- **Hold miniz_oxide at `=0.9.0`.** flate2 1.1.11 accepts it, and it
still has 0.8.9's rule; 0.9.1's only other changes affect wasm32. The
costs:
- No crate of ours depends on miniz_oxide directly, so this needs a
pinned direct dependency in `Cargo.toml` and a `crate.spec` in
`bazel/rust.MODULE.bazel`.
  - It moves backtrace's copy back from 0.9.1.
  - It only defers the decision.
- **Measure first.** Keep the old rule, ship a check in `decode_wasm`
that counts decoded modules with the rejected shape in a metric, and
switch once mainnet reports none for a release. The costs:
- `decode_wasm` runs in the compiler sandbox, so the count has to come
back with the compilation result.
- Modules are only decoded when a canister is installed or executes, so
idle canisters and stored snapshots stay unchecked.

# Other changes

- **Error text:** a gzip module whose deflate data is truncated, but
whose size trailer looks plausible, now fails with "failed to decode
compressed Wasm module: incomplete deflate stream". Before, it was "...:
unexpected end of file". The text appears in reject messages, and no
test asserts it. Most truncated uploads fail the module size check
before reaching flate2.
- **Raw-deflate and zlib decoders** now report truncated input as an
error instead of returning partial output, and zlib streams missing
their Adler-32 trailer now fail. Where this applies, all off-chain:
- **ICP Rosetta** (@dfinity/defi): request bodies with
`Content-Encoding: deflate` that are truncated or lack the trailer are
now rejected instead of parsed. Truncated gzip bodies only get a
different error. Bodies with the newly rejected table shape are rejected
too. ICRC Rosetta doesn't decompress requests.
- **ic-response-verification's raw `DeflateDecoder`,** for v1-certified
`deflate` responses. It runs in PocketIC's HTTP gateway and in the
ic-gateway binary that GuestOS ships for cloud engine nodes.
- **Other gzip decoders:** two places use the same gzip decoder on
inputs from standard compressors:
- the `.tar.gz` branch of `ic-http-utils`' archive extraction, which
only the orchestrator calls, to fetch the registry store during subnet
recovery;
  - PocketIC.
- **Compression:**
- **Unchanged:** one-shot gzip and raw-deflate output is byte-identical
at every level.
  - **Changed:**
- zlib-wrapped output at level 0 changes only its 2-byte header (`08 1D`
→ `78 01`);
    - output in flush edge cases;
    - output of `read::GzEncoder` and `bufread::GzEncoder` at level 1.
- **Production use:** production code compresses with flate2 only for
ic-boundary's and ic-gateway's `/metrics` responses, through tower-http
at the default level. Nothing stores, hashes or certifies those bytes.
No production canister links flate2, so all 44 canisters in
`//publish/canisters` are byte-identical with and without this change
(PR base 4b4fc5d).
- **Requirements and locks:**
- flate2's requirement goes from `1.0.31` to `1.1.11` in `Cargo.toml`
and `bazel/rust.MODULE.bazel`.
  - miniz_oxide 0.8.9 drops out of both locks.
- zlib-rs 0.6.8, an optional flate2 backend, appears in them but isn't
built.
- miniz_oxide 0.9.1 gains its `default`, `simd` and `with-alloc`
features, which backtrace's copy now also gets.
- flate2's new default feature `runtime_detection` only enables
crc32fast's `std` feature, which was already on.
  - No other package changes version.

# Verification

- **Locks:** in the dev container, `cargo update --workspace` reports
"Locking 0 packages". `./bin/bazel-pin.sh` reports "Nothing to repin.",
and `MODULE.bazel.lock` doesn't change.
- **Lint:** `./ci/scripts/rust-lint.sh` passes.
- **Tests:** these pass on the rebased head:
  - `//rs/embedders:embedders_test`;
  - `//rs/embedders:embedders_integration_tests/misc_tests`;
-
`//rs/execution_environment:execution_environment_misc_integration_tests/execution_test_test`,
which installs gzipped modules;
  - the `//rs/http_utils` tests.
- **Evidence:** the figures above come from:
- differential tests of miniz_oxide 0.8.9 and 0.9.1 and of flate2 1.1.5,
1.1.9 and 1.1.11 against zlib;
  - encoder experiments;
  - decoding the module corpus;
  - the dashboard sample;
  - local builds of `//publish/canisters` with and without this change.

For each part except the dashboard sample, a second AI agent re-checked
the first one's findings with its own code and runs. The figures above
include its corrections. The scripts and raw results are not in the
repo.

This PR carries the `CI_ALL_BAZEL_TARGETS` label.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants