Skip to content

fix(artifacts): reject non-object GLB JSON roots and non-array images - #14297

Merged
vincentkoc merged 1 commit into
morluto:mainfrom
Plastic-time:rrfz/fix-glb-json-root-shape
Nov 26, 2026
Merged

vincentkoc merged 1 commit into
morluto:mainfrom
Plastic-time:rrfz/fix-glb-json-root-shape

Conversation

@Plastic-time

@Plastic-time Plastic-time commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #14296.

glbLayout (src/artifacts/gpuAsset/GpuAssetLayouts.ts) no longer silently coerces non-object GLB JSON roots, non-array images members, non-object buffers entries, or explicit byteOffset: null values into empty defaults. Non-object JSON roots now report json_status: "invalid" and coverage.status: "unknown", and invalid images / bufferView / buffer / byteOffset declarations keep coverage unknown with explicit limitations.

Problem and expected behavior

On origin/main (271bad782), glbLayout used recordOf(...) (coercing any non-object to {}), arrayOf(...) (coercing any non-array to []), and view["byteOffset"] ?? 0 (coercing null to 0):

  • Non-object JSON roots ([], null, 42, "text", true): parseLastWinsJson(...) returned the valid non-object JSON value, recordOf(...) turned it into {}, and jsonStatus was set to "parsed", reporting coverage.status: "complete" and limitations: [] in contradiction to the existing limitation "The GLB JSON chunk is not a readable JSON object; collection counts were not read.".
  • Non-array images member ("images": "not-an-array", {}, null, 0, false): arrayOf(json["images"]) treated the invalid member as an empty array without setting regionsExamined = "unknown" or recording a limitation, reporting coverage.status: "complete".
  • Non-object buffers[0] (buffers: [null]) and explicit byteOffset: null: buffers[0] passed buffer === undefined and null ?? 0 turned byteOffset: null into 0, listing images/0.png with coverage.status: "complete".

Expected behavior:

  • Non-object JSON roots stay json_status: "invalid", set regionsExamined: "unknown", retain chunks/0.json / chunks/1.bin, and emit the existing limitation.
  • A JSON root whose own images property is not an array keeps json_status: "parsed", sets regionsExamined: "unknown", and emits "The GLB images member is not a JSON array; embedded images were not listed.".
  • Non-object image / bufferView / buffer entries and explicit byteOffset: null or out-of-bounds byteOffset / byteLength count as unresolved images (regionsExamined: "unknown").

Change and scope

  • src/artifacts/gpuAsset/GpuAssetLayouts.ts:
    • Replaced recordOf(...) (silent fallback to {}) with asRecord(...) returning Readonly<Record<string, unknown>> | undefined, and extracted readGlbJsonChunk(...) to keep chunk parsing flat and readable.
    • Required asRecord(parseLastWinsJson(...)) !== undefined before returning { status: "parsed", json: parsed } (non-objects return { status: "invalid", json: {} }, triggering regionsExamined = "unknown" and the existing non-object JSON limitation).
    • Checked Object.hasOwn(json, "images") && !Array.isArray(json["images"]) to mark regionsExamined = "unknown" and record "The GLB images member is not a JSON array; embedded images were not listed.".
    • Validated image, bufferViews[viewIndex], and buffers[bufferIndex] with asRecord(...), treated view["byteOffset"] === undefined (omitted) separately from null, and checked start > binLength || length > binLength - start so start + length avoids exceeding Number.MAX_SAFE_INTEGER.
  • Sibling audit (no other production files needed changes):
    • Audited sibling GPU formats in GpuAssetLayouts.ts (ddsLayout, ktxLayout, ktx2Layout — binary headers only, no JSON).
    • Audited sibling JSON root readers across src/artifacts/, src/resources/, src/domain/, and src/native/parsers/: src/native/parsers/plist.ts (the only other caller of parseLastWinsJson) explicitly tracks rootKind: "invalid" | "container" | "scalar"; src/resources/AsarHeader.ts rejects json-not-object at probe time; src/domain/sourceMapFormat.ts validates the root with mapHeaderSchema.
  • Scope: ordinary parser boundary fix within existing GLB inventory authority; contribution scope maintainer decision is not applicable.

Contract and boundary impact

  • Semantic owner and earliest changed stage: glbLayout in src/artifacts/gpuAsset/GpuAssetLayouts.ts owns GLB JSON chunk interpretation and embedded image region discovery, consumed by GpuAssetArtifactReader (src/artifacts/gpuAsset/GpuAssetArtifactReader.ts) and inspect-artifact / extract-artifact. Removed the silent-coercion recordOf helper and replaced it with asRecord.
  • Contribution scope fit and linked maintainer decision: not applicable (existing static GLB header parser fix; no new provider, execution, mutation, or protection recovery).
  • CLI and MCP/tool-catalog contract: unchanged schema (glbMetadataSchema already defines json_status: "parsed" | "invalid" | "limit" and coverage.status: "complete" | "unknown"). Malformed GLB JSON roots and invalid images declarations now report unknown coverage and limitations instead of complete.
  • Provider, bridge, target-format, or platform compatibility: applies to GLB v2 containers inspected through GpuAssetArtifactReader / inspect-artifact / extract-artifact.
  • Evidence, artifact, provenance, or reconstruction contract: prevents fabricated json_status: "parsed" and coverage.status: "complete" claims while retaining raw chunk regions (chunks/0.json, chunks/1.bin) and valid sibling image regions.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • 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/artifacts/gpuAsset/GpuAssetLayouts.test.ts (new, 21 tests): covers all five non-object JSON roots ([], null, 42, "text", true), valid object controls (omitted images, images: [], embedded image with omitted byteOffset at exact binLength alongside URI external images), five non-array images types (string, object, null, number, boolean), and eight invalid image/bufferView/buffer/byteOffset shapes (non-object images[0] preserving images/1.png, non-array bufferViews, non-object bufferView, non-array buffers, non-object buffers[0], explicit byteOffset: null, byteOffset > binLength with byteLength: 0, and byteOffset + byteLength = binLength + 1).
    • src/artifacts/gpuAsset/GpuAssetArtifactReader.test.ts: adds 2 tests verifying GpuAssetArtifactReader on a non-object JSON root ([]) and inventoryArtifact on a non-array images member ({}).
    • tests/acceptance/gpuAssetHeadersCli.test.ts: adds 1 compiled CLI test verifying rea inspect-artifact <array-root.glb> --json exits 0 with coverage.status: "unknown", format_metadata.json_status: "invalid", and the non-object JSON limitation.
  • Base reproduction or other evidence (executed on Windows 11 x64, Node v24.22.1, base 271bad782, fix 3edfaa153):
    • A/B regression check (new tests only on clean base 271bad782):
      npm run test:local -- src/artifacts/gpuAsset/GpuAssetLayouts.test.ts src/artifacts/gpuAsset/GpuAssetArtifactReader.test.ts -> 14 failed | 38 passed (52) (GpuAssetLayouts.test.ts: 12 failed / 9 passed; GpuAssetArtifactReader.test.ts: 2 failed / 29 passed).
    • Same command on fix 3edfaa153:
      52 passed (52) (GpuAssetLayouts.test.ts: 21/21 passed; GpuAssetArtifactReader.test.ts: 31/31 passed).
    • Line mutation check on 271bad782..3edfaa153: 27/30 killed against npm run test:local -- src/artifacts/gpuAsset/GpuAssetLayouts.test.ts (all newly introduced guards killed; the 3 surviving lines are the 2 TypeScript return-type annotation lines of readGlbJsonChunk stripped by Vitest and enforced by tsc, plus the pre-existing length > GLB_JSON_PARSE_BYTES check moved unchanged into readGlbJsonChunk).
  • User-visible CLI/MCP output (if applicable): rea inspect-artifact array-root.glb --json now outputs coverage.status: "unknown", limitations: ["The GLB JSON chunk is not a readable JSON object; collection counts were not read."], and root format_metadata.json_status: "invalid" instead of complete / parsed (verified in tests/acceptance/gpuAssetHeadersCli.test.ts).
  • Remaining proof gaps:
    • Linux/macOS CI workflows have not run yet on this branch.
    • Local compiled CLI verification used a pre-built Windows native addon (6.9.0 binary labeled 6.10.1 in an ignored manifest.json) to satisfy build checks; GpuAssetLayouts and GpuAssetArtifactReader are pure TypeScript and do not invoke the native addon.

Boundary regressions covered: non-object JSON roots, non-array images members, non-object nested image/bufferView/buffer records, explicit byteOffset: null vs omitted byteOffset, exact binLength (MAX) vs binLength + 1 (MAX + 1), and preservation of valid sibling regions when an invalid sibling is present. Lifecycle regressions are not applicable because no descriptors, processes, or cleanup stages were modified.

For evidence-bearing changes:

  • 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/artifacts/gpuAsset/GpuAssetLayouts.test.ts src/artifacts/gpuAsset/GpuAssetArtifactReader.test.ts — passed (2 files, 52/52 tests).
  • npm run test:focused -- tests/acceptance/gpuAssetHeadersCli.test.ts — passed (1 file, 7/7 compiled CLI tests).
  • npm run check:fast — passed (typecheck, lint, and verify:architecture-guards across 3085 source files).

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Valid glTF 2.0 GLB files with object JSON roots and valid images / bufferViews / buffers declarations continue to report json_status: "parsed" and coverage.status: "complete".
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable (in-process GLB header/layout parser verified through unit, reader, inventory, and compiled CLI tests).
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: stops silent type coercion of malformed GLB JSON structures and avoids start + length exceeding Number.MAX_SAFE_INTEGER; no new dependencies, network calls, or process launches.

Author readiness

Human owner: @Plastic-time

  • 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.

Stop coercing non-object GLB JSON roots, non-array images members,
non-object buffer entries, and explicit null byteOffset values to
empty defaults in glbLayout. Non-object roots now report
json_status: "invalid" with unknown coverage, and non-array images
or invalid image/bufferView/buffer declarations keep coverage unknown
with explicit limitations.
@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable defects were found.

Summary

Tightens GLB parsing so malformed JSON shapes no longer look like complete inventories.

  • GLB inventory marks malformed JSON declarations as unknown.
  • Embedded images appear only when their GLB byte ranges resolve.

Review was based on source inspection; tests were not run. Whether this PR has been superseded could not be checked because GitHub access was unavailable.

Reviews (2) · Last reviewed commit: "fix(artifacts): reject non-object GLB JS..." · Reviewed by Greptile

@Plastic-time
Plastic-time marked this pull request as ready for review November 24, 2026 07:10
@chatgpt-codex-connector

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-24T07:10:15.645790Z
We couldn’t complete this review. Comment @codex review to try again.
3edfaa1 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.

@vincentkoc
vincentkoc merged commit b9a5855 into morluto:main Nov 26, 2026
40 of 41 checks passed
@morluto morluto added area: evidence Evidence, artifacts, and reconstruction bug Something isn't working labels Nov 26, 2026
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 bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] GLB layout reports non-object JSON roots as parsed and non-array images as complete

3 participants