faiss-defuse 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- faiss_defuse/__init__.py +53 -0
- faiss_defuse/_adapter.py +113 -0
- faiss_defuse/_allowlist.py +71 -0
- faiss_defuse/_demo.py +155 -0
- faiss_defuse/_docstate.py +85 -0
- faiss_defuse/_faiss_header.py +142 -0
- faiss_defuse/_jsontags.py +243 -0
- faiss_defuse/_loader.py +118 -0
- faiss_defuse/_pickle_scan.py +311 -0
- faiss_defuse/_store.py +612 -0
- faiss_defuse/_stub_decode.py +271 -0
- faiss_defuse/_verify.py +164 -0
- faiss_defuse/cli.py +376 -0
- faiss_defuse/errors.py +91 -0
- faiss_defuse/i18n.py +42 -0
- faiss_defuse/limits.py +32 -0
- faiss_defuse/locales/en.json +104 -0
- faiss_defuse/locales/ko.json +104 -0
- faiss_defuse/py.typed +0 -0
- faiss_defuse-0.1.1.dist-info/METADATA +334 -0
- faiss_defuse-0.1.1.dist-info/RECORD +24 -0
- faiss_defuse-0.1.1.dist-info/WHEEL +4 -0
- faiss_defuse-0.1.1.dist-info/entry_points.txt +2 -0
- faiss_defuse-0.1.1.dist-info/licenses/LICENSE +21 -0
faiss_defuse/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""faiss-defuse: inspect, convert and load LangChain FAISS stores without executing pickle.
|
|
2
|
+
|
|
3
|
+
The core (scan, header reading, convert, inspect) uses only the standard library.
|
|
4
|
+
``load_safe``, ``save_safe`` and the top-k part of ``verify`` need the ``[langchain]`` extra.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ._faiss_header import FaissHeader, read_faiss_header
|
|
10
|
+
from ._loader import load_safe, save_safe
|
|
11
|
+
from ._pickle_scan import Finding, ScanReport, scan, scan_bytes
|
|
12
|
+
from ._store import Manifest, StoreInfo, convert, inspect
|
|
13
|
+
from ._verify import VerifyReport, verify
|
|
14
|
+
from .errors import (
|
|
15
|
+
DefuseError,
|
|
16
|
+
MalformedStoreError,
|
|
17
|
+
ManifestMismatchError,
|
|
18
|
+
MissingExtraError,
|
|
19
|
+
OptionConflictError,
|
|
20
|
+
OutputExistsError,
|
|
21
|
+
UnsafePickleError,
|
|
22
|
+
UnsupportedContentError,
|
|
23
|
+
)
|
|
24
|
+
from .limits import Limits
|
|
25
|
+
|
|
26
|
+
__version__ = "0.1.1"
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DefuseError",
|
|
30
|
+
"FaissHeader",
|
|
31
|
+
"Finding",
|
|
32
|
+
"Limits",
|
|
33
|
+
"MalformedStoreError",
|
|
34
|
+
"Manifest",
|
|
35
|
+
"ManifestMismatchError",
|
|
36
|
+
"MissingExtraError",
|
|
37
|
+
"OptionConflictError",
|
|
38
|
+
"OutputExistsError",
|
|
39
|
+
"ScanReport",
|
|
40
|
+
"StoreInfo",
|
|
41
|
+
"UnsafePickleError",
|
|
42
|
+
"UnsupportedContentError",
|
|
43
|
+
"VerifyReport",
|
|
44
|
+
"__version__",
|
|
45
|
+
"convert",
|
|
46
|
+
"inspect",
|
|
47
|
+
"load_safe",
|
|
48
|
+
"read_faiss_header",
|
|
49
|
+
"save_safe",
|
|
50
|
+
"scan",
|
|
51
|
+
"scan_bytes",
|
|
52
|
+
"verify",
|
|
53
|
+
]
|
faiss_defuse/_adapter.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""The only module that touches faiss, numpy and LangChain.
|
|
2
|
+
|
|
3
|
+
Everything LangChain-specific lives here so that a successor package for the
|
|
4
|
+
(archived) langchain-community FAISS wrapper needs a change in one place. The
|
|
5
|
+
constructor call follows langchain-community 0.4.x.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib.util
|
|
11
|
+
import warnings
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Callable
|
|
14
|
+
|
|
15
|
+
from ._docstate import DecodedDoc
|
|
16
|
+
from .errors import MissingExtraError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _has(module: str) -> bool:
|
|
20
|
+
try:
|
|
21
|
+
return importlib.util.find_spec(module) is not None
|
|
22
|
+
except (ImportError, ValueError):
|
|
23
|
+
return False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def extras_available() -> bool:
|
|
27
|
+
return all(_has(m) for m in ("faiss", "numpy", "langchain_core", "langchain_community"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def require_langchain(what: str) -> None:
|
|
31
|
+
if not extras_available():
|
|
32
|
+
raise MissingExtraError(what)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def faiss_available() -> bool:
|
|
36
|
+
return _has("faiss") and _has("numpy")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _import_faiss() -> Any:
|
|
40
|
+
import faiss # noqa: PLC0415
|
|
41
|
+
|
|
42
|
+
return faiss
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def read_index(path: str | Path) -> Any:
|
|
46
|
+
"""``faiss.read_index`` - callers must have validated the file first."""
|
|
47
|
+
return _import_faiss().read_index(str(path))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def write_index(index: Any, path: str | Path) -> None:
|
|
51
|
+
_import_faiss().write_index(index, str(path))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _langchain() -> tuple[Any, Any, Any, Any]:
|
|
55
|
+
with warnings.catch_warnings():
|
|
56
|
+
warnings.simplefilter("ignore", DeprecationWarning) # langchain-community announces its sunset on import
|
|
57
|
+
from langchain_community.docstore.in_memory import InMemoryDocstore
|
|
58
|
+
from langchain_community.vectorstores import FAISS
|
|
59
|
+
from langchain_community.vectorstores.utils import DistanceStrategy
|
|
60
|
+
from langchain_core.documents import Document
|
|
61
|
+
return FAISS, InMemoryDocstore, DistanceStrategy, Document
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_faiss(
|
|
65
|
+
embeddings: Any,
|
|
66
|
+
index: Any,
|
|
67
|
+
docs: dict[str, DecodedDoc],
|
|
68
|
+
idmap: dict[int, str],
|
|
69
|
+
options: dict[str, Any],
|
|
70
|
+
relevance_score_fn: Callable[[float], float] | None,
|
|
71
|
+
) -> Any:
|
|
72
|
+
FAISS, InMemoryDocstore, DistanceStrategy, Document = _langchain()
|
|
73
|
+
docstore = InMemoryDocstore(
|
|
74
|
+
{key: Document(page_content=d.page_content, metadata=d.metadata, id=d.doc_id) for key, d in docs.items()}
|
|
75
|
+
)
|
|
76
|
+
kwargs: dict[str, Any] = {"normalize_L2": bool(options["normalize_L2"])}
|
|
77
|
+
if options.get("distance_strategy"):
|
|
78
|
+
kwargs["distance_strategy"] = DistanceStrategy[options["distance_strategy"]]
|
|
79
|
+
with warnings.catch_warnings():
|
|
80
|
+
warnings.simplefilter("ignore", UserWarning) # "Normalizing L2 is not applicable ..." is about the caller's choice
|
|
81
|
+
return FAISS(embeddings, index, docstore, dict(idmap), relevance_score_fn=relevance_score_fn, **kwargs)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def live_parts(vectorstore: Any) -> tuple[Any, dict[str, DecodedDoc], dict[int, str], dict[str, Any]]:
|
|
85
|
+
"""Read index, documents, id map and options from a live LangChain ``FAISS`` object."""
|
|
86
|
+
_, InMemoryDocstore, _, _ = _langchain()
|
|
87
|
+
docstore = getattr(vectorstore, "docstore", None)
|
|
88
|
+
if not isinstance(docstore, InMemoryDocstore):
|
|
89
|
+
raise TypeError(
|
|
90
|
+
"save_safe supports FAISS stores backed by InMemoryDocstore only "
|
|
91
|
+
f"(got {type(docstore).__name__}). Use FAISS.from_documents()/from_texts()."
|
|
92
|
+
)
|
|
93
|
+
docs: dict[str, DecodedDoc] = {}
|
|
94
|
+
for key, doc in docstore._dict.items():
|
|
95
|
+
docs[key] = DecodedDoc(doc.page_content, dict(doc.metadata), getattr(doc, "id", None))
|
|
96
|
+
strategy = getattr(vectorstore.distance_strategy, "name", str(vectorstore.distance_strategy))
|
|
97
|
+
options = {"distance_strategy": strategy, "normalize_L2": bool(vectorstore._normalize_L2), "source": "recorded"}
|
|
98
|
+
return vectorstore.index, docs, dict(vectorstore.index_to_docstore_id), options
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_local_trusted(path: str | Path, dim: int, index_name: str) -> tuple[dict[str, DecodedDoc], dict[int, str]]:
|
|
102
|
+
"""Open the ORIGINAL pickle with LangChain's loader. Only used by ``verify --trust-original``.
|
|
103
|
+
|
|
104
|
+
This executes the pickle; the caller opts in explicitly because they built the store themselves.
|
|
105
|
+
"""
|
|
106
|
+
FAISS, _, _, _ = _langchain()
|
|
107
|
+
from langchain_core.embeddings import DeterministicFakeEmbedding
|
|
108
|
+
|
|
109
|
+
vs = FAISS.load_local(
|
|
110
|
+
str(path), DeterministicFakeEmbedding(size=dim), index_name=index_name, allow_dangerous_deserialization=True
|
|
111
|
+
)
|
|
112
|
+
docs = {k: DecodedDoc(v.page_content, dict(v.metadata), getattr(v, "id", None)) for k, v in vs.docstore._dict.items()}
|
|
113
|
+
return docs, dict(vs.index_to_docstore_id)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Allow-lists. Everything not listed here is refused by the scanner.
|
|
2
|
+
|
|
3
|
+
Two groups:
|
|
4
|
+
|
|
5
|
+
* ``STRUCT`` - the classes LangChain itself writes into ``index.pkl``.
|
|
6
|
+
* ``VALUES`` - plain value types that may appear inside document metadata.
|
|
7
|
+
|
|
8
|
+
The decoder never imports any of these modules. It maps each pair to an inert
|
|
9
|
+
stub or to a small function of our own (see ``_stub_decode``).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
DOCSTORE_NAMES = frozenset(
|
|
15
|
+
{
|
|
16
|
+
("langchain_community.docstore.in_memory", "InMemoryDocstore"),
|
|
17
|
+
("langchain.docstore.in_memory", "InMemoryDocstore"),
|
|
18
|
+
}
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
DOCUMENT_NAMES = frozenset(
|
|
22
|
+
{
|
|
23
|
+
("langchain_core.documents.base", "Document"),
|
|
24
|
+
("langchain.schema.document", "Document"),
|
|
25
|
+
("langchain.docstore.document", "Document"),
|
|
26
|
+
}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
STRUCT = DOCSTORE_NAMES | DOCUMENT_NAMES
|
|
30
|
+
|
|
31
|
+
VALUES = frozenset(
|
|
32
|
+
{
|
|
33
|
+
("builtins", "set"),
|
|
34
|
+
("__builtin__", "set"),
|
|
35
|
+
("builtins", "frozenset"),
|
|
36
|
+
("__builtin__", "frozenset"),
|
|
37
|
+
("builtins", "object"),
|
|
38
|
+
("__builtin__", "object"),
|
|
39
|
+
("collections", "OrderedDict"),
|
|
40
|
+
("copyreg", "_reconstructor"),
|
|
41
|
+
("_codecs", "encode"),
|
|
42
|
+
("datetime", "date"),
|
|
43
|
+
("datetime", "datetime"),
|
|
44
|
+
("datetime", "time"),
|
|
45
|
+
("datetime", "timedelta"),
|
|
46
|
+
("datetime", "timezone"),
|
|
47
|
+
("numpy", "dtype"),
|
|
48
|
+
("numpy.core.multiarray", "scalar"),
|
|
49
|
+
("numpy._core.multiarray", "scalar"),
|
|
50
|
+
}
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
ALLOWED_GLOBALS = STRUCT | VALUES
|
|
54
|
+
|
|
55
|
+
# Types that are known and harmless but that this version cannot turn into JSON.
|
|
56
|
+
# They are reported as "unsupported", not "unsafe".
|
|
57
|
+
KNOWN_UNSUPPORTED = frozenset(
|
|
58
|
+
{
|
|
59
|
+
("pandas._libs.tslibs.timestamps", "_unpickle_timestamp"),
|
|
60
|
+
("pandas._libs.tslibs.timestamps", "Timestamp"),
|
|
61
|
+
("pandas._libs.tslibs.timedeltas", "_timedelta_unpickle"),
|
|
62
|
+
("numpy.core.multiarray", "_reconstruct"),
|
|
63
|
+
("numpy._core.multiarray", "_reconstruct"),
|
|
64
|
+
("numpy", "ndarray"),
|
|
65
|
+
("decimal", "Decimal"),
|
|
66
|
+
("uuid", "UUID"),
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Modules LangChain used before the split into langchain-core / -community.
|
|
71
|
+
LEGACY_MODULE_PREFIXES = ("langchain.",)
|
faiss_defuse/_demo.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Offline practice material: builds sample stores and walks through scan -> convert -> verify -> load_safe.
|
|
2
|
+
|
|
3
|
+
Everything here is real behaviour on real files; only the embeddings are the
|
|
4
|
+
fake, deterministic kind (``DeterministicFakeEmbedding``), so search quality is
|
|
5
|
+
meaningless. The "malicious" sample runs a harmless ``echo`` that would create a
|
|
6
|
+
sentinel file if - and only if - someone unpickled it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import pickle
|
|
13
|
+
import shlex
|
|
14
|
+
import shutil
|
|
15
|
+
import sys
|
|
16
|
+
import types
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Iterator
|
|
21
|
+
|
|
22
|
+
from . import _adapter
|
|
23
|
+
from ._pickle_scan import ScanReport, scan
|
|
24
|
+
from ._store import convert, load_original
|
|
25
|
+
from ._verify import VerifyReport, verify
|
|
26
|
+
|
|
27
|
+
SENTINEL_NAME = "PWNED"
|
|
28
|
+
_SENTENCES = [
|
|
29
|
+
"FAISS stores vectors in a binary file.",
|
|
30
|
+
"LangChain keeps document text in a pickle next to it.",
|
|
31
|
+
"A pickle is a list of instructions, not plain data.",
|
|
32
|
+
"Unpickling can import modules and call functions.",
|
|
33
|
+
"A scan can read the instructions without running them.",
|
|
34
|
+
"Hashes in a manifest catch changes after the build.",
|
|
35
|
+
"Metadata can hold dates, tuples and sets.",
|
|
36
|
+
"Cosine and L2 distance rank results differently.",
|
|
37
|
+
"Chunking decides what a retriever can find.",
|
|
38
|
+
"Embeddings turn text into points in space.",
|
|
39
|
+
"Deterministic fake embeddings make demos repeatable.",
|
|
40
|
+
"Every store should be verified before it ships.",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def make_clean_store(directory: Path, *, count: int = 12) -> None:
|
|
45
|
+
"""Write a real ``FAISS.save_local`` store (fake embeddings) into ``directory``."""
|
|
46
|
+
_adapter.require_langchain("demo")
|
|
47
|
+
import datetime as dt
|
|
48
|
+
|
|
49
|
+
from langchain_core.documents import Document
|
|
50
|
+
from langchain_core.embeddings import DeterministicFakeEmbedding
|
|
51
|
+
|
|
52
|
+
FAISS, _, _, _ = _adapter._langchain()
|
|
53
|
+
docs = [
|
|
54
|
+
Document(
|
|
55
|
+
page_content=_SENTENCES[i % len(_SENTENCES)] + f" (#{i})",
|
|
56
|
+
metadata={"source": f"note-{i}.md", "page": i, "date": dt.date(2025, 1, 1 + i % 28), "tags": ("demo", f"t{i % 3}")},
|
|
57
|
+
id=f"doc-{i}",
|
|
58
|
+
)
|
|
59
|
+
for i in range(count)
|
|
60
|
+
]
|
|
61
|
+
store = FAISS.from_documents(docs, DeterministicFakeEmbedding(size=32))
|
|
62
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
store.save_local(str(directory))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@contextmanager
|
|
67
|
+
def _legacy_modules() -> Iterator[tuple[type, type]]:
|
|
68
|
+
"""Temporarily register fake pre-split LangChain modules so a legacy-shaped pickle can be written."""
|
|
69
|
+
names = ["langchain", "langchain.docstore", "langchain.docstore.in_memory", "langchain.schema", "langchain.schema.document"]
|
|
70
|
+
saved = {n: sys.modules.get(n) for n in names}
|
|
71
|
+
for n in names:
|
|
72
|
+
sys.modules[n] = types.ModuleType(n)
|
|
73
|
+
|
|
74
|
+
class InMemoryDocstore:
|
|
75
|
+
def __init__(self, data: dict[str, Any]) -> None:
|
|
76
|
+
self._dict = data
|
|
77
|
+
|
|
78
|
+
class Document:
|
|
79
|
+
def __init__(self, content: str, metadata: dict[str, Any]) -> None:
|
|
80
|
+
self.__dict__.update(page_content=content, metadata=metadata, lookup_str="", lookup_index=0, type="Document")
|
|
81
|
+
|
|
82
|
+
def __getstate__(self) -> dict[str, Any]:
|
|
83
|
+
return {"__dict__": dict(self.__dict__), "__fields_set__": {"page_content", "metadata"}}
|
|
84
|
+
|
|
85
|
+
InMemoryDocstore.__qualname__ = "InMemoryDocstore"
|
|
86
|
+
Document.__qualname__ = "Document"
|
|
87
|
+
InMemoryDocstore.__module__ = "langchain.docstore.in_memory"
|
|
88
|
+
Document.__module__ = "langchain.schema.document"
|
|
89
|
+
sys.modules["langchain.docstore.in_memory"].InMemoryDocstore = InMemoryDocstore # type: ignore[attr-defined]
|
|
90
|
+
sys.modules["langchain.schema.document"].Document = Document # type: ignore[attr-defined]
|
|
91
|
+
try:
|
|
92
|
+
yield InMemoryDocstore, Document
|
|
93
|
+
finally:
|
|
94
|
+
for n, mod in saved.items():
|
|
95
|
+
if mod is None:
|
|
96
|
+
sys.modules.pop(n, None)
|
|
97
|
+
else:
|
|
98
|
+
sys.modules[n] = mod
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def make_legacy_store(directory: Path, clean: Path) -> None:
|
|
102
|
+
"""Re-write ``clean`` in the old ``langchain.*`` module layout (Pydantic v1 style state)."""
|
|
103
|
+
original = load_original(clean)
|
|
104
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
shutil.copyfile(original.faiss_path, directory / "index.faiss")
|
|
106
|
+
with _legacy_modules() as (Docstore, Document):
|
|
107
|
+
docstore = Docstore({k: Document(d.page_content, d.metadata) for k, d in original.store.docs.items()})
|
|
108
|
+
(directory / "index.pkl").write_bytes(pickle.dumps((docstore, original.store.index_to_docstore_id), protocol=4))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class _Payload:
|
|
112
|
+
"""Pickles to ``os.system(<echo ...>)`` - harmless, but leaves a file behind if executed."""
|
|
113
|
+
|
|
114
|
+
def __init__(self, command: str) -> None:
|
|
115
|
+
self.command = command
|
|
116
|
+
|
|
117
|
+
def __reduce__(self) -> tuple[Any, tuple[str]]:
|
|
118
|
+
return (os.system, (self.command,))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def make_malicious_store(directory: Path, clean: Path, sentinel: Path) -> None:
|
|
122
|
+
"""A store whose ``index.pkl`` would write ``sentinel`` if it were ever unpickled."""
|
|
123
|
+
original = load_original(clean)
|
|
124
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
125
|
+
shutil.copyfile(original.faiss_path, directory / "index.faiss")
|
|
126
|
+
command = f"echo faiss-defuse-demo-payload > {shlex.quote(str(sentinel))}"
|
|
127
|
+
(directory / "index.pkl").write_bytes(pickle.dumps((_Payload(command), original.store.index_to_docstore_id), protocol=4))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass
|
|
131
|
+
class DemoResult:
|
|
132
|
+
out: Path
|
|
133
|
+
clean: ScanReport
|
|
134
|
+
malicious: ScanReport
|
|
135
|
+
legacy: ScanReport
|
|
136
|
+
verify: VerifyReport
|
|
137
|
+
sentinel: Path
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def sentinel_exists(self) -> bool:
|
|
141
|
+
return self.sentinel.exists()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def run_demo(out: Path) -> DemoResult:
|
|
145
|
+
"""Build the samples under ``out`` and run the whole flow. Never unpickles anything."""
|
|
146
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
sentinel = out / SENTINEL_NAME
|
|
148
|
+
sentinel.unlink(missing_ok=True)
|
|
149
|
+
clean, legacy, malicious, converted = out / "clean", out / "legacy", out / "malicious", out / "converted"
|
|
150
|
+
make_clean_store(clean)
|
|
151
|
+
make_legacy_store(legacy, clean)
|
|
152
|
+
make_malicious_store(malicious, clean, sentinel)
|
|
153
|
+
reports = {"clean": scan(clean), "malicious": scan(malicious), "legacy": scan(legacy)}
|
|
154
|
+
convert(clean, converted, overwrite=True)
|
|
155
|
+
return DemoResult(out, reports["clean"], reports["malicious"], reports["legacy"], verify(converted, original=clean), sentinel)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Normalise the state of stubbed LangChain objects (Pydantic v1, v2 or plain dict)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
from .errors import MalformedStoreError
|
|
9
|
+
|
|
10
|
+
_KNOWN_KEYS = {"page_content", "metadata", "id", "type"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class DecodedDoc:
|
|
15
|
+
"""One document as plain data."""
|
|
16
|
+
|
|
17
|
+
page_content: str
|
|
18
|
+
metadata: dict[Any, Any]
|
|
19
|
+
doc_id: str | None = None
|
|
20
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _no_charge(n: int) -> None:
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _state_dict(stub: Any, what: str, charge: Callable[[int], None] = _no_charge) -> dict[Any, Any]:
|
|
28
|
+
"""Copy of the stub's attribute dict. ``charge(n)`` is called before ``n`` entries are copied
|
|
29
|
+
(one shared state dict may sit behind many documents; see ``_stub_decode._DecodeBudget``)."""
|
|
30
|
+
state = getattr(stub, "state", None)
|
|
31
|
+
# Pydantic v2 writes {"__dict__": ..., "__pydantic_fields_set__": ...}; v1 writes
|
|
32
|
+
# {"__dict__": ..., "__fields_set__": ...}; very old objects were plain dicts.
|
|
33
|
+
if isinstance(state, dict):
|
|
34
|
+
if "__dict__" in state and isinstance(state["__dict__"], dict):
|
|
35
|
+
charge(len(state["__dict__"]))
|
|
36
|
+
inner = dict(state["__dict__"])
|
|
37
|
+
extra = state.get("__pydantic_extra__")
|
|
38
|
+
if isinstance(extra, dict):
|
|
39
|
+
charge(len(extra))
|
|
40
|
+
for key, value in extra.items():
|
|
41
|
+
inner.setdefault(key, value)
|
|
42
|
+
return inner
|
|
43
|
+
charge(len(state))
|
|
44
|
+
return dict(state)
|
|
45
|
+
if isinstance(state, tuple) and len(state) == 2 and isinstance(state[0], dict):
|
|
46
|
+
charge(len(state[0]))
|
|
47
|
+
return dict(state[0])
|
|
48
|
+
raise MalformedStoreError(
|
|
49
|
+
f"unexpected {what} state of type {type(state).__name__}.", code="unexpected-structure"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def normalize_docstore(docstore: Any, document_cls: type, charge: Callable[[int], None] = _no_charge) -> dict[str, Any]:
|
|
54
|
+
"""Return ``{docstore_id: document_stub}`` from an ``InMemoryDocstore`` stub."""
|
|
55
|
+
state = _state_dict(docstore, "docstore", charge)
|
|
56
|
+
inner = state.get("_dict")
|
|
57
|
+
if not isinstance(inner, dict):
|
|
58
|
+
raise MalformedStoreError(
|
|
59
|
+
f"docstore state has no '_dict' mapping (keys: {sorted(map(str, state))}).",
|
|
60
|
+
code="unexpected-structure",
|
|
61
|
+
)
|
|
62
|
+
for key, value in inner.items():
|
|
63
|
+
if not isinstance(key, str) or not isinstance(value, document_cls):
|
|
64
|
+
raise MalformedStoreError(
|
|
65
|
+
"docstore entries must be str -> Document.", code="unexpected-structure"
|
|
66
|
+
)
|
|
67
|
+
return inner
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def normalize_doc(doc_id: str, stub: Any, document_cls: type, charge: Callable[[int], None] = _no_charge) -> DecodedDoc:
|
|
71
|
+
state = _state_dict(stub, f"document {doc_id!r}", charge)
|
|
72
|
+
content = state.get("page_content")
|
|
73
|
+
if not isinstance(content, str):
|
|
74
|
+
raise MalformedStoreError(
|
|
75
|
+
f"document {doc_id!r} has no text page_content (keys: {sorted(map(str, state))}).",
|
|
76
|
+
code="unexpected-structure",
|
|
77
|
+
)
|
|
78
|
+
metadata = state.get("metadata", {})
|
|
79
|
+
if not isinstance(metadata, dict):
|
|
80
|
+
raise MalformedStoreError(f"document {doc_id!r} metadata is not a mapping.", code="unexpected-structure")
|
|
81
|
+
inner_id = state.get("id")
|
|
82
|
+
if inner_id is not None and not isinstance(inner_id, str):
|
|
83
|
+
raise MalformedStoreError(f"document {doc_id!r} has a non-string id.", code="unexpected-structure")
|
|
84
|
+
extra = {str(k): v for k, v in state.items() if k not in _KNOWN_KEYS and not str(k).startswith("__")}
|
|
85
|
+
return DecodedDoc(page_content=content, metadata=metadata, doc_id=inner_id, extra=extra)
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Read and validate the header of a FAISS index file without importing faiss.
|
|
2
|
+
|
|
3
|
+
Layout (faiss-cpu 1.16.0, little endian): 4-byte fourcc, int32 d, int64 ntotal,
|
|
4
|
+
two int64 dummies, uint8 is_trained, int32 metric_type and, when metric_type > 1,
|
|
5
|
+
a float32 metric_arg. Flat indexes continue with a uint64 element count followed
|
|
6
|
+
by ``count`` float32 values, so their exact file size is known.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import struct
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .errors import MalformedStoreError
|
|
17
|
+
from .limits import Limits
|
|
18
|
+
|
|
19
|
+
# fourcc -> LangChain-facing index name. Anything else is refused before faiss reads it.
|
|
20
|
+
FOURCC_NAMES: dict[str, str] = {
|
|
21
|
+
"IxF2": "IndexFlatL2",
|
|
22
|
+
"IxFI": "IndexFlatIP",
|
|
23
|
+
"IxFl": "IndexFlat",
|
|
24
|
+
"IHNf": "IndexHNSWFlat",
|
|
25
|
+
"IwFl": "IndexIVFFlat",
|
|
26
|
+
"IxMp": "IndexIDMap",
|
|
27
|
+
"IxM2": "IndexIDMap2",
|
|
28
|
+
"IxPq": "IndexPQ",
|
|
29
|
+
}
|
|
30
|
+
_FLAT = {"IxF2", "IxFI", "IxFl"}
|
|
31
|
+
_ID_MAPPED = {"IxMp", "IxM2"}
|
|
32
|
+
_METRICS = {0: "inner_product", 1: "L2", 2: "L1", 3: "Linf", 4: "Lp", 20: "Canberra", 21: "BrayCurtis", 22: "JensenShannon", 23: "Jaccard"}
|
|
33
|
+
_BASE = struct.Struct("<4siqqqBi") # fourcc, d, ntotal, dummy, dummy, is_trained, metric_type
|
|
34
|
+
_MAX_DIM = 65536
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class FaissHeader:
|
|
39
|
+
"""Facts read from the first bytes of ``index.faiss``."""
|
|
40
|
+
|
|
41
|
+
fourcc: str
|
|
42
|
+
index_type: str
|
|
43
|
+
d: int
|
|
44
|
+
ntotal: int
|
|
45
|
+
is_trained: bool
|
|
46
|
+
metric_type: int
|
|
47
|
+
metric_arg: float | None
|
|
48
|
+
file_size: int
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def metric_name(self) -> str:
|
|
52
|
+
return _METRICS.get(self.metric_type, str(self.metric_type))
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def id_mapped(self) -> bool:
|
|
56
|
+
return self.fourcc in _ID_MAPPED
|
|
57
|
+
|
|
58
|
+
def to_dict(self) -> dict[str, Any]:
|
|
59
|
+
return {
|
|
60
|
+
"fourcc": self.fourcc,
|
|
61
|
+
"index_type": self.index_type,
|
|
62
|
+
"d": self.d,
|
|
63
|
+
"ntotal": self.ntotal,
|
|
64
|
+
"is_trained": self.is_trained,
|
|
65
|
+
"metric_type": self.metric_type,
|
|
66
|
+
"metric_name": self.metric_name,
|
|
67
|
+
"metric_arg": self.metric_arg,
|
|
68
|
+
"file_size": self.file_size,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def read_faiss_header(path: str | Path, *, limits: Limits = Limits()) -> FaissHeader:
|
|
73
|
+
"""Validate and return the header of a FAISS index file.
|
|
74
|
+
|
|
75
|
+
Raises :class:`MalformedStoreError` (``code`` is ``unsupported-index-type`` or
|
|
76
|
+
``bad-faiss-header``) before anything is handed to ``faiss.read_index``.
|
|
77
|
+
"""
|
|
78
|
+
p = Path(path)
|
|
79
|
+
try:
|
|
80
|
+
file_size = p.stat().st_size
|
|
81
|
+
with p.open("rb") as fh:
|
|
82
|
+
head = fh.read(_BASE.size + 4 + 8)
|
|
83
|
+
except OSError as exc:
|
|
84
|
+
raise MalformedStoreError(f"cannot read {p}: {exc.strerror or exc}", code="missing-file",
|
|
85
|
+
params={"path": str(p)}) from None
|
|
86
|
+
if file_size > limits.max_faiss_bytes:
|
|
87
|
+
raise MalformedStoreError(
|
|
88
|
+
f"{p.name} is {file_size} bytes, above the limit of {limits.max_faiss_bytes}. "
|
|
89
|
+
"Raise Limits.max_faiss_bytes if this size is expected.",
|
|
90
|
+
code="limit-exceeded", params={"limit": "max_faiss_bytes"},
|
|
91
|
+
)
|
|
92
|
+
if len(head) < _BASE.size:
|
|
93
|
+
raise MalformedStoreError(f"{p.name} is truncated ({file_size} bytes); not a FAISS index.", code="bad-faiss-header")
|
|
94
|
+
raw_fourcc, d, ntotal, _d1, _d2, trained, metric = _BASE.unpack_from(head)
|
|
95
|
+
fourcc = raw_fourcc.decode("latin1")
|
|
96
|
+
if fourcc not in FOURCC_NAMES:
|
|
97
|
+
raise MalformedStoreError(
|
|
98
|
+
f"{p.name} has index type {fourcc!r}, which is not on the supported list "
|
|
99
|
+
f"({', '.join(sorted(FOURCC_NAMES))}). It was not passed to faiss.",
|
|
100
|
+
code="unsupported-index-type",
|
|
101
|
+
)
|
|
102
|
+
if not 1 <= d <= _MAX_DIM:
|
|
103
|
+
raise MalformedStoreError(f"{p.name} claims dimension d={d} (allowed 1..{_MAX_DIM}).", code="bad-faiss-header")
|
|
104
|
+
if not 0 <= ntotal <= limits.max_vectors:
|
|
105
|
+
raise MalformedStoreError(f"{p.name} claims ntotal={ntotal} (allowed 0..{limits.max_vectors}).", code="bad-faiss-header")
|
|
106
|
+
if trained not in (0, 1):
|
|
107
|
+
raise MalformedStoreError(f"{p.name} has an invalid is_trained byte ({trained}).", code="bad-faiss-header")
|
|
108
|
+
if metric not in _METRICS:
|
|
109
|
+
raise MalformedStoreError(f"{p.name} has unknown metric_type {metric}.", code="bad-faiss-header")
|
|
110
|
+
offset = _BASE.size
|
|
111
|
+
metric_arg: float | None = None
|
|
112
|
+
if metric > 1:
|
|
113
|
+
if len(head) < offset + 4:
|
|
114
|
+
raise MalformedStoreError(f"{p.name} is truncated inside the header.", code="bad-faiss-header")
|
|
115
|
+
(metric_arg,) = struct.unpack_from("<f", head, offset)
|
|
116
|
+
offset += 4
|
|
117
|
+
if fourcc in _FLAT:
|
|
118
|
+
if len(head) < offset + 8:
|
|
119
|
+
raise MalformedStoreError(f"{p.name} is truncated inside the header.", code="bad-faiss-header")
|
|
120
|
+
(count,) = struct.unpack_from("<Q", head, offset)
|
|
121
|
+
if count != ntotal * d:
|
|
122
|
+
raise MalformedStoreError(
|
|
123
|
+
f"{p.name}: vector count {count} does not equal ntotal*d = {ntotal * d}.", code="bad-faiss-header"
|
|
124
|
+
)
|
|
125
|
+
expected = offset + 8 + count * 4
|
|
126
|
+
if file_size != expected:
|
|
127
|
+
raise MalformedStoreError(
|
|
128
|
+
f"{p.name} is {file_size} bytes but a flat index with ntotal={ntotal}, d={d} must be {expected}.",
|
|
129
|
+
code="bad-faiss-header",
|
|
130
|
+
)
|
|
131
|
+
elif file_size < offset + 8:
|
|
132
|
+
raise MalformedStoreError(f"{p.name} is truncated ({file_size} bytes).", code="bad-faiss-header")
|
|
133
|
+
return FaissHeader(
|
|
134
|
+
fourcc=fourcc,
|
|
135
|
+
index_type=FOURCC_NAMES[fourcc],
|
|
136
|
+
d=d,
|
|
137
|
+
ntotal=ntotal,
|
|
138
|
+
is_trained=bool(trained),
|
|
139
|
+
metric_type=metric,
|
|
140
|
+
metric_arg=metric_arg,
|
|
141
|
+
file_size=file_size,
|
|
142
|
+
)
|