Skip to content

bug/fallback-encoding-detection-for-file-like-objects #4434

Open

Description

@ujjwalredd

Describe the bug
Currently, when trying to determine a file type from its initial text (text_head), the parser attempts fallback character-set detection only for physical file paths. For file-like objects (e.g., SpooledTemporaryFile, BytesIO streams), it blindly decodes the first 4096 bytes using the default encoding (usually UTF-8) with errors="ignore". This can strip characters and lead to corrupted text or incorrect filetype classification when ingesting documents from cloud storage (S3/GCS) or APIs.

To Reproduce
Pass a non-UTF-8 encoded BytesIO object to detect_filetype.

Expected behavior
File-like objects should use the same detect_file_encoding fallback mechanism as physical file paths to avoid data loss on decoding errors.

Screenshots
N/A

Environment Info
N/A - General bug in filetype.py

Additional context
Resolves the TODO in filetype.py:text_head.

Activity

  1. feiiiiii5 commented on Aug 15, 2026

    @feiiiiii5
    Contributor

    Opened PR #4438: text_head() now applies the same detect_file_encoding() fallback to file-like objects as it does to file paths, replacing the errors="ignore" decode that silently stripped characters. Two tests cover it (wrong-encoding-arg correction + latin-1 regression).

  2. ayam04 commented on Sep 22, 2026

    @ayam04

    Taking this one. Plan: route file-like objects through the same detect_file_encoding fallback the path-based branch already uses before the 4096-byte text_head decode, plus a regression with a non-UTF-8 BytesIO.

  3. ayam04 commented on Sep 22, 2026

    @ayam04

    Status update: the text_head half of this is already fixed and merged — #4438 (released in 0.26.3) added the detect_file_encoding fallback to the file-like branch.

    The same class of gap still existed in the remaining read path in that module: _FileTypeDetector._disambiguate_json_file_type() read bytes and decoded them with the declared encoding using errors="ignore", so a non-UTF-8 (e.g. UTF-16) JSON/NDJSON payload lost characters and a multi-record payload classified as JSON instead of NDJSON — for file-like objects and file paths alike.

    I opened #4494 to close that path (shares one _decode_head_bytes() helper with text_head, with regression tests). This issue can be closed once that lands, or right away if you consider #4438 to have covered it.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions