Skip to content

fix: keep signature-identified binaries binary instead of guessing UTF-16 - #198310

Closed
qingminglong wants to merge 1 commit into
openclaw:mainfrom
qingminglong:pr/fix-binaries-classified-as-utf16
Closed

qingminglong wants to merge 1 commit into
openclaw:mainfrom
qingminglong:pr/fix-binaries-classified-as-utf16

Conversation

@qingminglong

@qingminglong qingminglong commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #198289

What Problem This Solves

Fixes: binary attachments are decoded as UTF-16 text and ~60,000 characters of garbage are inlined into the model prompt when the file carries a NUL-heavy byte signature (SQLite, ELF, PE, Java class, OTF, WASM).

User Impact

A database backup, executable, or font sent as an attachment now reaches the model as an unsupported binary reference instead of a wall of decoded garbage, so the turn is answered normally instead of being refused. No configuration change, migration, or user action is required.

Why This Change Was Made

classifyAttachmentBytes fell through to a text re-sniff for every payload that did not resolve to a text MIME. In that branch resolveUtf16Charset derives utf-16le/utf-16be from the NUL ratio alone, so a SQLite header followed by page padding read as UTF-16 and was decoded into printable-looking characters. A MIME that already classifies as binary is a magic-byte verdict about the payload, not an extension guess, so the classifier now returns binary for it and leaves only the BOM case to the decoder branch. Byte-detected archives keep archive, and genuine BOM-prefixed UTF-16 text still reaches the decoder.

Evidence

  • Regression test red→green: magic-byte binary signatures outrank a NUL-driven UTF-16 guess (7 cases: SQLite, SQLite behind a .txt name, ELF, PE, Java class, OTF, WASM). With the fix reverted the file reports Tests 7 failed | 14 passed (21); with the fix applied it reports Tests 21 passed (21) in 5.06 s.

  • Targeted suite: node scripts/run-vitest.mjs run packages/media-core/src/attachment-classify.test.ts → Test Files 1 passed (1), Tests 21 passed (21). The 14 pre-existing classification cases (UTF-8 truncation, UTF-16 with/without BOM, PNG, ZIP, octet-stream, YAML allowlist) are unchanged and still pass.

  • Behavior verification, classifyAttachmentBytes({ declaredMime: "application/octet-stream", name: "*.db" }) before → after:

    Payload Before the fix After the fix
    SQLite text/plain, utf-16le application/x-sqlite3, binary
    ELF text/plain, utf-16le application/x-elf, binary
    OTF text/plain, utf-16be font/otf, binary
    PE text/plain, utf-16le application/x-msdownload, binary
    Java class text/plain, utf-16le application/java-vm, binary
    WASM text/plain, utf-16le application/wasm, binary
  • oxlint on both changed files: 0 warnings, 0 errors. oxfmt --check: clean.

  • tsgo -p tsconfig.core.json: 64 errors on this branch and 64 on the parent commit — identical count, all from a pre-existing @babel/types 7/8 duplicate in this local install, and none of them names attachment-classify or media-core. Verified with grep -c 'error TS' on both sides plus grep -c attachment-classify → 0.

  • Scope: only packages/media-core/src/attachment-classify.ts (+8 lines) and its test file (+47 lines). The downstream document-context renderer, the MIME sniffer, and the file-type dependency are untouched.

This proves the classifier no longer converts signature-identified binaries into text. It does not prove the end-to-end prompt size on a live gateway, which depends on the existing [Unsupported document format] path in the inbound document context.

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The PR prevents recognized binary attachment types from falling through to UTF-16 text inference.

Example: Send a NUL-padded SQLite database named t.db with application/octet-stream metadata.

  • Before: The classifier returns text/plain with a guessed UTF-16 charset.
  • After: The classifier returns application/x-sqlite3 with class binary.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful focused repair, blocked by a CI-confirmed text-extraction regression and absent shipped-entry-point proof.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Sending a binary attachment can inline approximately 60,000 garbage characters and make subsequent agent replies fail.
Reason: Recognized-signature handling is valuable, but the linked issue also reports unknown binary bytes that this patch leaves on the original inference path; use Related rather than Closes unless that remaining scope is resolved.

Merge readiness

⛔ Blocked before merge - 3 items remain

This PR addresses a real attachment bug, but its guard also rejects recoverable text MIME hints; an existing extraction regression fails in CI.

Priority: P1
Reviewed head: 117c6c3b7e4c780d488f93ab844f3c637ebbc16d

Before merge

  • Add real behavior proof - Supplied classifier tests and before/after classification results exercise the changed helper, but no shipped Gateway or channel run demonstrates the resulting document context; the body explicitly acknowledges that gap. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Restrict the binary return to MIME types established by bytes (P1) - detectMime also returns header metadata when bytes and filename provide no type, so a nonempty binary-class MIME does not establish a magic-byte match. For the existing base64 input containing bytes 63 61 66 e9 20 80 and mediaType plain; charset=windows-1252, this return preserves MIME plain instead of recovering text/plain and decoding café €; extraction then throws Unsupported file MIME type: plain. The changed-node CI annotation confirms this exact failure in the existing extraction suite. Preserve metadata-only text inference while applying precedence to actual byte-detected binaries.
  • Explain or restore the original intent of Fallback text recovery - 97ea9f7: Preserve inferred Windows-1252 text and carry its decoder; the new guard inadvertently bypasses that recovery for metadata-only binary-class MIME values.

Findings

  • [P1] Restrict the binary return to MIME types established by bytes — packages/media-core/src/attachment-classify.ts:185-186

Provenance

  • Fallback text recovery changes intended behavior without addressing why it exists (97ea9f7: Preserve inferred Windows-1252 text and carry its decoder; the new guard inadvertently bypasses that recovery for metadata-only binary-class MIME values.)

Tests

  • Missing end-to-end proof: Show a real SQLite attachment through a shipped Gateway or channel producing the unsupported-format marker without decoded garbage, with IPs, keys, phone numbers, and private endpoints redacted.
Agent review details

How this fits together

The shared media-core classifier combines attachment bytes and MIME hints into one classification consumed by extraction and inbound document-context rendering.

flowchart TD
  A[Attachment bytes and metadata] --> B[MIME detection]
  B --> C[Shared attachment classifier]
  C --> D[Text and PDF extraction]
  C --> E[Unsupported format marker]
  D --> F[Agent document context]
  E --> F
Loading

Technical review

Best possible solution:

Keep binary-signature precedence in the shared classifier while preserving text recovery for metadata-only MIME hints and tracking unknown-binary handling separately.

Do we have a high-confidence way to reproduce the issue?

The linked report provides an official-release SQLite reproduction, and current-main source exposes the same fall-through; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The shared classifier is the correct repair owner, but a resolved MIME is not necessarily a byte signature, so the guard needs a narrower condition.

Full review comments:

  • [P1] Restrict the binary return to MIME types established by bytes — packages/media-core/src/attachment-classify.ts:185-186
    detectMime also returns header metadata when bytes and filename provide no type, so a nonempty binary-class MIME does not establish a magic-byte match. For the existing base64 input containing bytes 63 61 66 e9 20 80 and mediaType plain; charset=windows-1252, this return preserves MIME plain instead of recovering text/plain and decoding café €; extraction then throws Unsupported file MIME type: plain. The changed-node CI annotation confirms this exact failure in the existing extraction suite. Preserve metadata-only text inference while applying precedence to actual byte-detected binaries.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 25559c477004.

Provenance checked

  • Shared binary/text classification keeps the original intent (746a188: The merged consolidation established one classification result for MIME admission and extraction.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

Acceptance criteria:

  • node scripts/run-vitest.mjs run packages/media-core/src/attachment-classify.test.ts packages/media-core/src/mime.test.ts src/media/input-files.extract.test.ts src/media-understanding/file-context.test.ts
  • pnpm exec oxlint packages/media-core/src/attachment-classify.ts packages/media-core/src/attachment-classify.test.ts
  • pnpm exec oxfmt --check packages/media-core/src/attachment-classify.ts packages/media-core/src/attachment-classify.test.ts
  • git diff --check

What I checked:

PR surface

Source +8, Tests +47. Total +55 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 8 0 +8
Tests 1 47 0 +47
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 55 0 +55

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: same_root_cause
Canonical: #198289
Summary: The issue and competing PRs address binary attachments entering text inference in the shared classifier.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The linked official-release report shows binary attachments filling model context with garbage and repeatedly preventing useful replies.
  • merge-risk: 🚨 compatibility: The new guard breaks an existing supported text-recovery input, confirmed by the extraction test failure in CI.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 13, 2026, 9:47 AM ET / 14:47 UTC.

@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Thanks @qingminglong for working on #198289. We landed #198309 (afa871c), the earliest of the three fixes, which keeps an attachment binary when its magic bytes match the resolved type and leaves the BOM, extension and text-hint paths unchanged. Closing this one as a duplicate; your work helped confirm the cause.

@obviyus obviyus closed this Nov 13, 2026
@qingminglong

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and fixed a regression introduced by the first revision of this PR.

checks-node-changed-4 failed on src/media/input-files.extract.test.ts > decodes base64 text: MIME recovery plain; charset=windows-1252 with Unsupported file MIME type: plain.

Root cause. A malformed Content-Type such as plain; charset=windows-1252 normalizes to the bare token plain. attachmentClassFromMime classifies that as binary for lack of a recognised prefix — but it is not a verdict about the payload. The new short-circuit treated it as one and skipped the text-recovery path below, so the caller received mime: "plain".

Fix. Require a well-formed type/subtype essence before trusting the classification, so only real magic-byte verdicts keep a binary classification.

input class mime charset
windows-1252 bytes + plain; charset=windows-1252 text text/plain windows-1252
SQLite header binary application/x-sqlite3 —
WASM header binary application/wasm —

packages/media-core/src/attachment-classify.test.ts: 21 passed, including the magic-byte cases that motivated #198289.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Binary attachments (SQLite, ELF, PE, …) are classified as UTF-16 text and ~60k chars of garbage are inlined into the model prompt

2 participants