Skip to content

feat(artifacts): decode UnityFS LZMA blocks - #14699

Merged
morluto merged 11 commits into
morluto:mainfrom
BeqaKs:cursor/unityfs-lzma-decode-a7dc
Nov 27, 2026
Merged

morluto merged 11 commits into
morluto:mainfrom
BeqaKs:cursor/unityfs-lzma-decode-a7dc

Conversation

@BeqaKs

@BeqaKs BeqaKs commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #14176. UnityFS AssetBundles that use Unity's default LZMA block compression (type 1) no longer report members as hash_status: unavailable. LZMA blocks and blocks-info tables decode with the existing lzma-purejs dependency so inventory can hash, compare, and extract members the same way LZ4 bundles already do.

Problem and expected behavior

Before: compression 1 data blocks and blocks-info tables were refused as unsupported; members kept directory names/sizes but had no content hash or child artifact.

After: valid Unity LZMA streams (5-byte properties plus raw data, size taken from the block table) decode under the existing 64 MiB per-block and archive plaintext-work budgets, and members report verified hashes when the stream is well-formed. Malformed LZMA remains a format error. Other codecs (for example LZHAM) stay unsupported.

Change and scope

  • Add decodeUnityLzmaBlock in src/compression/LzmaUnityBlock.ts: synthesize an LZMA-Alone size field from the declared uncompressed length, bound output while decoding, and reuse the small-dictionary promotion already needed by lzma-purejs.
  • Wire compression 1 through UnityFsStructures / UnityFsArtifactReader for both blocks-info tables and data blocks.
  • Update synthetic fixtures to encode Unity-shaped LZMA; flip prior refusal tests to successful decode and add malformed/LZHAM regressions.
  • Docs and the UnityFS reader limitation string no longer claim LZMA is unsupported.

Intentionally not included: routing UnityFS through the UEFI owned worker process (LZ4 already decodes in-process; the same admission pattern is applied here), LZHAM, encryption, and re-running the external UnityPy corpus samples in CI.

Contribution scope: ordinary format inspection within the existing UnityFS reader. Maintainer scope decision: not applicable.

Contract and boundary impact

  • Semantic owner and earliest changed stage: UnityFsStructures / UnityFsArtifactReader own UnityFS block decode; consumers (inspect-artifact, extract-artifact, compare-artifacts) see verified member hashes instead of unavailable compression 1.
  • Contribution scope fit and linked maintainer decision: format inspection; not applicable.
  • CLI and MCP/tool-catalog contract: none (behavior change only for already-classified unityfs inputs).
  • Provider, bridge, target-format, or platform compatibility: portable Node decode via existing lzma-purejs; no new dependency.
  • Evidence, artifact, provenance, or reconstruction contract: LZMA members can now produce content hashes and child artifacts; coverage becomes complete when every member decodes.
  • Target selection, authority, upstream behavior, and cleanup details: not applicable (read-only artifact path).
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: src/compression/LzmaUnityBlock.test.ts (round-trip, truncated header, bad properties, unfinished stream, budget); UnityFsArtifactReader.test.ts (LZMA blocks-info inventory, member decode, malformed member, LZHAM still unknown); boundaries/CLI/MCP fixtures updated from LZMA refusal to verified decode; unsupported-compression probes now use LZHAM (4).

  • Base reproduction or other evidence: prior tests pinned blocksInfoCompression: 1 / blockCompression: 1 as unsupported; those now expect directory availability and member bytes.

  • User-visible CLI/MCP output: inspect-artifact on an LZMA member reports hash_status: verified and coverage: complete in the updated CLI/MCP expectations.

  • Remaining proof gaps: Cytoid character_kaede and UnityPy xinzexi_2_n_tex were not re-run in this environment; synthetic Unity-shaped LZMA covers the codec path.

  • Observed, derived, and inferred claims remain distinguishable.

  • Artifact identity, source provenance, and failed attempts remain preserved.

  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run test:local -- src/compression/LzmaUnityBlock.test.ts src/artifacts/UnityFsArtifactReader.test.ts src/artifacts/UnityFsArtifactReader.boundaries.test.ts — 3 files, 60 tests passed.
  • Full-project tsc --noEmit was attempted but killed by host memory limits; Vitest transform of the changed modules succeeded under the focused run above.
  • Compiled CLI/MCP suites were not rebuilt in this environment; their expectations were updated in source to match the new behavior.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Bundles that previously inventoried with unavailable LZMA members now hash those members when the stream is valid.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: read-only decode with the same per-block output budget as LZ4; dictionary declarations above that budget are refused.

Author readiness

Human owner: @BeqaKs

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Author checklist (completed by the PR author before requesting review)

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.
  • I ran every test, build, or measurement needed to validate this change, reported a browser, GPU, or environment gap only when that runtime or hardware is unavailable, and reported the checks I ran and their results without presenting inferred correctness or speedups as measured.
  • Comments explain constraints or non-obvious decisions; task history and conversations stay out of code and docs.
  • Documentation is concise and factual, without punchy slogans or promotional language.
  • This change fixes the root cause and follows the engineering rules in AGENTS.md.
  • Formatted input is interpreted once at the owning boundary, and consumers use the owner's parsed facts. See Interpret boundary facts once.
  • Combined failures preserve partial observations, remaining resources, and cleanup facts. See Own the lifecycle.
  • A hardcoded limit is an REA_ runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T14:54:49.022559Z
We couldn’t complete this review. Comment @codex review to try again.
9c30d99 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed changes appear safe to merge.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed changes appear safe to merge.

Summary

Adds LZMA support for UnityFS data blocks and directory tables.

  • UnityFS readers decode LZMA tables and member blocks.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[UnityFS compressed block] --> B{Supported compression?}
  B -->|No| C[Keep available directory facts]
  B -->|Yes| D{Within block budgets?}
  D -->|No| E[Keep directory and name the exceeded budget]
  D -->|Yes| F[Decode LZ4 or LZMA]
  F --> G[Read member bytes and compute hashes]
Loading

Reviews (10) · Last reviewed commit: "fix(unityfs): name the encoded or decode..." · Reviewed by Greptile

Comment thread src/compression/LzmaUnityBlock.ts Resolved
Comment thread src/compression/LzmaUnityBlock.ts Resolved
Comment thread src/compression/LzmaUnityBlock.ts Resolved
Comment thread docs/unityfs.md Resolved
Comment thread src/compression/LzmaUnityBlock.ts Resolved
Comment thread src/compression/LzmaUnityBlock.ts Resolved
@morluto morluto added area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request labels Nov 26, 2026
@BeqaKs
BeqaKs marked this pull request as draft November 26, 2026 14:54
@BeqaKs
BeqaKs marked this pull request as ready for review November 26, 2026 14:54
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@BeqaKs BeqaKs closed this Nov 26, 2026
@BeqaKs BeqaKs reopened this Nov 26, 2026
Unity's default AssetBundle compression (type 1) left members as
hash_status unavailable. Decode 5-byte Unity LZMA streams with the
existing lzma-purejs dependency so inventory can hash and extract them.
Architecture guards forbid raw Buffer numeric reads outside
binaryContainer; match the UEFI LZMA path.
Accept optional LZMA end markers without trailing junk, decode off-thread so
timer aborts land, return one expected-sized buffer, and mark xinzexi unverified.
Await worker.terminate() before settling abort/reply paths, and allocate the
synthesized alone header with allocUnsafeSlow so the worker receives it without
a second encoded-stream copy.
Retriggers Actions after the worker-exit follow-up push did not receive a
GitHub Actions check suite.
@BeqaKs
BeqaKs force-pushed the cursor/unityfs-lzma-decode-a7dc branch from cecc08d to c5ef3e9 Compare November 26, 2026 14:57
…de spec-valid streams

UnityFS writers emit one LZMA block for a whole data stream, so the per-block
decode budget refused the whole inventory of any LZMA bundle above 64 MiB,
where before this change the directory was retained. An over-budget block now
keeps the directory and only members inside it report an unavailable read
naming the budget, for LZ4 and LZMA alike.

The LZMA decoder window is bounded by the declared output instead of the
declared dictionary, so a large dictionary on a small block decodes and no
longer allocates a dictionary-sized window. Properties follow the LZMA
specification (lc 0-8, lp 0-4, pb 0-4) rather than the LZMA2 lc + lp limit.
Worker error events and exits without a reply stay runtime failures instead of
being reported as a malformed block.

Tests decode a liblzma-produced stream as a known answer, settle only after
the worker exits on completion and cancellation, and share one encoder.
Comment thread src/compression/LzmaUnityBlock.ts Resolved
Comment thread src/artifacts/UnityFsArtifactReader.ts Resolved
BeqaKs and others added 2 commits November 27, 2026 16:46
Overflow past the bundle's declared length is a format error, not a
decoder budget exhaustion. Declarations above maximumBytes still fail
closed as a resource limit before decode starts.
A block refused by its encoded size reported its decoded size against the decoded budget. The block now records which bound refused it, and the member read names that bound, its declared size and the budget.
@morluto

morluto commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Thanks for this. I reviewed the whole PR, merged main in (c2e9536), and pushed fixes on top in b8645a6 and b9b0024. Nothing was force-pushed.

Defects fixed

  1. Large LZMA bundles lost their whole inventory. UnityFS writers emit one LZMA block for a whole data stream (UnityPy's chunk_based_compress uses a 0xFFFFFFFF chunk size for LZMA). Extending the 64 MiB per-block decode check to LZMA made parseBlocks throw, so any LZMA bundle above 64 MiB failed to list, where main kept the directory with unknown member coverage. An over-budget block now keeps the directory, and only members inside it report an unavailable read naming the budget (blockUnavailability in UnityFsStructures.ts, unavailableMember in the reader). The rule is the same for LZ4 and LZMA, and the existing LZ4 boundary test now expects the retained directory.
  2. The window was sized from the dictionary, not the output. lzma-purejs allocates its whole window from the declared dictionary, so a small blocks-info table with UnityPy's 8 MiB dictionary allocated 8 MiB, and a dictionary above 64 MiB on any block was refused. Every valid match distance is below the bytes already produced, so the private LZMA-Alone copy now declares max(4 KiB, min(dictionary, declared output)). That decodes valid streams identically and still refuses an invalid distance. The SDK's own one-call LZMA2 path likewise uses the output buffer as its dictionary.
  3. Spec-valid properties were refused. lc + lp > 4 is an LZMA2 rule, which liblzma's encoder also enforces. The LZMA1 specification admits lc 0–8, lp 0–4 and pb 0–4 and only refuses props >= 225. The check now follows the specification.
  4. The refusal named the wrong bound (b9b0024). A block refused only for its encoded size reported its decoded size against the decoded budget. The block now records which bound refused it, and the read names that bound.
  5. Runtime failures were reported as a malformed target. A worker error event, or an exit without a reply, became BinaryFormatFailure("malformed"). Only decoder replies are now facts about the block. Worker out-of-memory becomes a resource failure, and other runtime errors pass through as raised.

Brittleness pass

  • Fixed:
    • the two copies of the lzma-purejs test encoder are now one fixture;
    • the worker source no longer repeats the size-field offset;
    • the magic properties bound is now a named, cited constant;
    • round-trip-only tests now include a known-answer stream from an independent encoder (CPython 3.14 liblzma, raw LZMA1, UnityPy's parameters, with an end marker);
    • the over-budget test covers both codecs and both table positions.
  • Left deliberately:
    • src/uefi/UefiLzmaWorker.ts decides the same LZMA properties, dictionary and range-coder facts separately, and has the same dictionary-versus-budget refusal as item 2. A shared src/compression LZMA core would remove the duplicate, but it changes UEFI behavior on main and is outside this PR, so I recommend a follow-up issue.
    • Streams that end in a marker still decode twice (known size, then unknown size). A single pass is possible, but it depends on lzma-purejs's flush timing, so I kept the simpler, correct path.
    • The 64 MiB per-block budget has no control yet, as before this PR.
  • Reference disagreement, left explicit: AssetStudio and AssetsTools.NET decode with the known output size, so their 7-Zip decoder stops there. UnityPy decodes without a size and expects an end marker. This PR accepts either ending and refuses other trailing bytes. Whether Unity itself ever writes trailing padding is unverified: no real Unity LZMA sample was rerun.

Threads

  • Worker exit: valid. Your 82fce30 fixed it, and a regression now proves that settlement waits for exit, on both cancellation and completion.
  • Size mismatch: your d3eebfa fixed it.
  • Encoded bound: fixed in b9b0024.

All three threads are replied to and resolved.

Sources

  • UnityPy BundleFile.decompress_data, CompressionHelper.decompress_lzma / compress_lzma and chunk_based_compress, via DeepWiki.
  • AssetStudio BundleFile.ReadBlocksInfoAndDirectory / ReadBlocks, and AssetsTools.NET SevenZipHelper, via DeepWiki.
  • 7-Zip LZMA SDK LzmaDec.h statuses (FINISHED_WITH_MARK, MAYBE_FINISHED_WITHOUT_MARK) and Lzma2Decode, via context7 and DeepWiki.
  • The LZMA SDK lzma-specification.txt.
  • lzma-purejs 0.9.3 OutWindow/Decoder source, read locally.

Validation

  • test:local on LzmaUnityBlock, UnityFsArtifactReader and its boundary tests: 75 passed. Each new regression fails on the previous head.
  • UnityFS CLI, LZ4 distance, MCP and acceptance boundary tests pass.
  • Typecheck, lint, architecture guards and the docs check pass.
  • The local dependency gate was bypassed because the shared node_modules is one knip patch behind main's lock. CI runs with clean installs.

@morluto
morluto merged commit a6cca9d into morluto:main Nov 27, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] UnityFS: decode LZMA blocks, Unity's default AssetBundle compression

2 participants