aido-onyx/smb-connector/app/sync.py
Naeem Dosh ee281da0e5 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>
2026-09-10 00:34:32 +05:00

213 lines
8.3 KiB
Python

"""The reconciliation engine: the production functionality the POC was missing.
For each source, one cycle:
1. Walk the mounted share, hashing each eligible file's content.
2. NEW / CHANGED (hash differs from the manifest) → upsert into Onyx.
3. GONE (in the manifest but no longer on disk) → delete from Onyx.
4. Reconcile against Onyx's own doc list so deletes still happen even if the
local manifest was lost (e.g. fresh volume).
Document ids are stable (derived from source name + relative path), so re-ingesting
a changed file updates it in place instead of creating a duplicate.
"""
from __future__ import annotations
import hashlib
import logging
import os
import re
from datetime import datetime, timezone
from .config import Config, SourceConfig
from .extract import extract_text
from .onyx_client import OnyxClient, OnyxError
from .state import FileRecord, State
logger = logging.getLogger("smb.sync")
def _source_slug(source_name: str) -> str:
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:
# 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.
digest = hashlib.sha256(f"{source_name}\x00{rel_path}".encode("utf-8")).hexdigest()[:20]
return f"smb_{_source_slug(source_name)}_{digest}"
def _source_id_prefix(source_name: str) -> str:
return f"smb_{_source_slug(source_name)}_"
def _logical_path(source: SourceConfig, rel_path: str) -> str:
# Present the Windows-style path the user recognises, mapped from the mount.
sep = "\\" if "\\" in source.normalized_logical() else "/"
joined = rel_path.replace("/", sep)
return f"{source.normalized_logical()}{sep}{joined}"
def _eligible(path: str, cfg: Config) -> bool:
ext = os.path.splitext(path)[1].lower().lstrip(".")
if cfg.include_ext and ext not in cfg.include_ext:
return False
try:
if os.path.getsize(path) > cfg.max_file_mb * 1024 * 1024:
logger.info("Skipping %s (> %d MB)", path, cfg.max_file_mb)
return False
except OSError:
return False
return not os.path.basename(path).startswith(".")
def _build_document(
source: SourceConfig, rel_path: str, doc_id: str, text: str, mtime: float
) -> dict:
logical = _logical_path(source, rel_path)
updated = datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat()
return {
"id": doc_id,
"source": "ingestion_api",
# semantic_identifier is the main label Onyx shows in the citation view.
"semantic_identifier": logical,
"title": os.path.basename(rel_path),
# A link is kept for reference; smb:// won't open in a browser (Phase 2
# replaces the broken preview with this path shown as copyable text).
"link": f"file://{logical}",
"sections": [{"text": text, "link": None}],
"metadata": {
"smb_source": source.name,
"logical_path": logical,
"relative_path": rel_path,
},
"doc_updated_at": updated,
}
def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: State) -> None:
if not os.path.isdir(source.mount):
logger.error("Source '%s': mount %s is not accessible — skipping", source.name, source.mount)
return
ss = state.source(source.name)
cc_pair_id = source.cc_pair_id or ss.cc_pair_id
if not cc_pair_id:
cc_pair_id = client.provision_cc_pair(f"AIDO SMB - {source.name}")
ss.cc_pair_id = cc_pair_id
state.save()
seen: set[str] = set()
upserts = deletes = unchanged = 0
for root, _dirs, files in os.walk(source.mount):
for fname in files:
abspath = os.path.join(root, fname)
if not _eligible(abspath, cfg):
continue
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)
try:
data = open(abspath, "rb").read()
except OSError as exc:
logger.warning("Cannot read %s: %s", abspath, exc)
continue
content_hash = hashlib.sha256(data).hexdigest()
prev = ss.files.get(rel)
if prev and prev.content_hash == content_hash:
unchanged += 1
continue
text = extract_text(abspath, data)
if not text.strip():
# Nothing extractable — don't ingest an empty document.
continue
doc_id = _stable_document_id(source.name, rel)
document = _build_document(source, rel, doc_id, text, os.path.getmtime(abspath))
try:
result = client.upsert_document(document, cc_pair_id)
except OnyxError as exc:
logger.error("Upsert failed for %s: %s", rel, exc)
continue
# Store the id Onyx actually persisted (it may normalise/encode the id),
# so later delete + reconcile match byte-for-byte.
canonical_id = result.get("document_id", doc_id) if isinstance(result, dict) else doc_id
ss.files[rel] = FileRecord(
document_id=canonical_id,
content_hash=content_hash,
logical_path=_logical_path(source, rel),
size=len(data),
mtime=os.path.getmtime(abspath),
)
upserts += 1
logger.info("%s %s", "updated" if prev else "indexed", rel)
# Deletes: files in the manifest but no longer on disk.
for rel in list(ss.files.keys()):
if rel in seen:
continue
rec = ss.files.pop(rel)
try:
client.delete_document(rec.document_id)
deletes += 1
logger.info("deleted %s (removed from share)", rel)
except OnyxError as exc:
logger.error("Delete failed for %s: %s", rel, exc)
ss.files[rel] = rec # keep it; retry next cycle
state.save()
# Manifest-independent reconcile: remove Onyx docs for this cc_pair that we
# no longer track (covers a lost manifest / externally-added docs).
try:
live_ids = {r.document_id for r in ss.files.values()}
for doc in client.list_cc_pair_documents(cc_pair_id):
did = doc.get("document_id")
if did and did.startswith(_source_id_prefix(source.name)) and did not in live_ids:
client.delete_document(did)
deletes += 1
logger.info("reconciled orphan delete %s", did)
except OnyxError as exc:
logger.warning("Reconcile pass for '%s' skipped: %s", source.name, exc)
logger.info(
"Source '%s' done: %d upserted, %d deleted, %d unchanged (cc_pair_id=%s)",
source.name, upserts, deletes, unchanged, cc_pair_id,
)
def sync_all(client: OnyxClient, cfg: Config, state: State) -> None:
for source in cfg.sources:
try:
sync_source(client, cfg, source, state)
except Exception as exc: # isolate a failing source from the rest
logger.exception("Source '%s' failed this cycle: %s", source.name, exc)