SMB connector: handle non-UTF-8 (Windows/Latin-1) filenames

Client hit a crash on every cycle: filenames with non-UTF-8 bytes (e.g. 0xE4 = ä)
arrive from os.walk surrogate-escaped ('\udce4'), and encoding them to UTF-8 for
the id hash / ingestion JSON / manifest raised UnicodeEncodeError.

Fix: normalise each relative path once via _fs_safe() — recover the real on-disk
bytes (os.fsencode reverses surrogateescape) and decode with the share's codepage
(SMB_FILENAME_ENCODING, default cp1252) — so the id hash, the ingestion payload
and the manifest are all UTF-8/JSON-safe and the filename displays correctly
(Angebot_März.txt, not a crash). New SMB_FILENAME_ENCODING env; the previously
added SMB_SOURCE_<N>_MOUNT_OPTS also lets you pass iocharset at mount time.

Verified E2E against live Onyx with a real 0xE4 filename: no crash, indexed
'Angebot_März.txt', logical path '\company\sales\Angebot_März.txt' stored
correctly, manifest persisted, restart → 0/0/all-unchanged (stable id).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Naeem Dosh 2026-09-10 00:34:32 +05:00
parent ab646927ed
commit ee281da0e5
3 changed files with 38 additions and 0 deletions

View file

@ -21,6 +21,12 @@ INCLUDE_EXTENSIONS=pdf,docx,txt,md,csv,xlsx,html,htm
MAX_FILE_MB=50 MAX_FILE_MB=50
LOG_LEVEL=INFO LOG_LEVEL=INFO
# Codepage for recovering filenames whose bytes aren't valid UTF-8 (common on
# Windows/Latin-1 shares, e.g. 0xE4 = ä). cp1252 = Western European (default).
# The connector handles such names correctly regardless of the CIFS mount charset;
# you can additionally pass iocharset via SMB_SOURCE_<N>_MOUNT_OPTS (see below).
SMB_FILENAME_ENCODING=cp1252
# ── Sources: SMB mounted INSIDE the container (recommended) ────────────────── # ── Sources: SMB mounted INSIDE the container (recommended) ──────────────────
# Give each share its SMB connection details and the connector mounts it itself # Give each share its SMB connection details and the connector mounts it itself
# (CIFS) — no host mount required. Uses the indexed style so each source can carry # (CIFS) — no host mount required. Uses the indexed style so each source can carry
@ -41,6 +47,9 @@ SMB_SOURCE_1_USERNAME=svc_onyx
SMB_SOURCE_1_PASSWORD=change-me SMB_SOURCE_1_PASSWORD=change-me
SMB_SOURCE_1_DOMAIN=COMPANY SMB_SOURCE_1_DOMAIN=COMPANY
# SMB_SOURCE_1_VERS=3.0 # SMB_SOURCE_1_VERS=3.0
# Extra raw CIFS mount options, appended verbatim to `mount -t cifs -o ...`.
# e.g. force the server's charset so filenames decode at mount time:
# SMB_SOURCE_1_MOUNT_OPTS=iocharset=utf8,nocase
# SMB_SOURCE_2_NAME=Legal # SMB_SOURCE_2_NAME=Legal
# SMB_SOURCE_2_SERVER=nas.company.local # SMB_SOURCE_2_SERVER=nas.company.local

View file

@ -56,6 +56,7 @@ class Config:
include_ext: set[str] include_ext: set[str]
max_file_mb: int max_file_mb: int
log_level: str log_level: str
filename_encoding: str = "cp1252"
sources: list[SourceConfig] = field(default_factory=list) sources: list[SourceConfig] = field(default_factory=list)
@ -139,6 +140,9 @@ def load_config() -> Config:
), ),
max_file_mb=int(os.environ.get("MAX_FILE_MB", "50")), max_file_mb=int(os.environ.get("MAX_FILE_MB", "50")),
log_level=os.environ.get("LOG_LEVEL", "INFO").upper(), log_level=os.environ.get("LOG_LEVEL", "INFO").upper(),
# Codepage used to recover filenames whose bytes aren't valid UTF-8 (common
# on Windows/Latin-1 shares, e.g. 0xE4 = ä). cp1252 covers Western European.
filename_encoding=os.environ.get("SMB_FILENAME_ENCODING", "cp1252"),
sources=_load_sources(), sources=_load_sources(),
) )
if not cfg.sources: if not cfg.sources:

View file

@ -31,6 +31,28 @@ def _source_slug(source_name: str) -> str:
return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src" return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src"
def _fs_safe(value: str, fallback_encoding: str) -> str:
"""Return a UTF-8/JSON-safe version of a filesystem string.
Filenames whose bytes are not valid UTF-8 arrive from os.walk as surrogate-
escaped strings (e.g. '\\udce4' for the Latin-1/CP1252 byte 0xE4 = 'ä').
Encoding those to UTF-8 — for the id hash, the ingestion JSON, or the manifest
— raises UnicodeEncodeError and crashes the cycle. Recover the original bytes
and decode them with the share's codepage so the real character comes through.
"""
try:
value.encode("utf-8")
return value # already clean UTF-8
except UnicodeEncodeError:
raw = os.fsencode(value) # reverse surrogateescape → original on-disk bytes
for enc in (fallback_encoding, "utf-8", "latin-1"):
try:
return raw.decode(enc)
except (UnicodeDecodeError, LookupError):
continue
return raw.decode("utf-8", "replace")
def _stable_document_id(source_name: str, rel_path: str) -> str: def _stable_document_id(source_name: str, rel_path: str) -> str:
# URL-safe id (no ':' etc.) so it is NOT re-encoded by Onyx — keeps the id we # URL-safe id (no ':' etc.) so it is NOT re-encoded by Onyx — keeps the id we
# send, store and later delete/reconcile byte-for-byte identical. # send, store and later delete/reconcile byte-for-byte identical.
@ -107,6 +129,9 @@ def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: St
if not _eligible(abspath, cfg): if not _eligible(abspath, cfg):
continue continue
rel = os.path.relpath(abspath, source.mount).replace(os.sep, "/") rel = os.path.relpath(abspath, source.mount).replace(os.sep, "/")
# Normalise non-UTF-8 filenames (surrogate-escaped) so the id hash,
# the ingestion payload and the manifest are all UTF-8/JSON-safe.
rel = _fs_safe(rel, cfg.filename_encoding)
seen.add(rel) seen.add(rel)
try: try:
data = open(abspath, "rb").read() data = open(abspath, "rb").read()