faiss-defuse 0.1.1__tar.gz
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-0.1.1/.gitignore +38 -0
- faiss_defuse-0.1.1/CHANGELOG.md +27 -0
- faiss_defuse-0.1.1/LICENSE +21 -0
- faiss_defuse-0.1.1/PKG-INFO +334 -0
- faiss_defuse-0.1.1/README.ko.md +310 -0
- faiss_defuse-0.1.1/README.md +308 -0
- faiss_defuse-0.1.1/docs/format.md +57 -0
- faiss_defuse-0.1.1/docs/images/code-diff.png +0 -0
- faiss_defuse-0.1.1/docs/images/convert-verify.ko.png +0 -0
- faiss_defuse-0.1.1/docs/images/convert-verify.png +0 -0
- faiss_defuse-0.1.1/docs/images/demo.ko.png +0 -0
- faiss_defuse-0.1.1/docs/images/demo.png +0 -0
- faiss_defuse-0.1.1/docs/images/inspect.ko.png +0 -0
- faiss_defuse-0.1.1/docs/images/inspect.png +0 -0
- faiss_defuse-0.1.1/docs/images/scan-safe.ko.png +0 -0
- faiss_defuse-0.1.1/docs/images/scan-safe.png +0 -0
- faiss_defuse-0.1.1/docs/images/scan-unsafe.ko.png +0 -0
- faiss_defuse-0.1.1/docs/images/scan-unsafe.png +0 -0
- faiss_defuse-0.1.1/pyproject.toml +58 -0
- faiss_defuse-0.1.1/src/faiss_defuse/__init__.py +53 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_adapter.py +113 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_allowlist.py +71 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_demo.py +155 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_docstate.py +85 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_faiss_header.py +142 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_jsontags.py +243 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_loader.py +118 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_pickle_scan.py +311 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_store.py +612 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_stub_decode.py +271 -0
- faiss_defuse-0.1.1/src/faiss_defuse/_verify.py +164 -0
- faiss_defuse-0.1.1/src/faiss_defuse/cli.py +376 -0
- faiss_defuse-0.1.1/src/faiss_defuse/errors.py +91 -0
- faiss_defuse-0.1.1/src/faiss_defuse/i18n.py +42 -0
- faiss_defuse-0.1.1/src/faiss_defuse/limits.py +32 -0
- faiss_defuse-0.1.1/src/faiss_defuse/locales/en.json +104 -0
- faiss_defuse-0.1.1/src/faiss_defuse/locales/ko.json +104 -0
- faiss_defuse-0.1.1/src/faiss_defuse/py.typed +0 -0
- faiss_defuse-0.1.1/tests/conftest.py +60 -0
- faiss_defuse-0.1.1/tests/helpers.py +134 -0
- faiss_defuse-0.1.1/tests/test_amplification.py +262 -0
- faiss_defuse-0.1.1/tests/test_cli.py +102 -0
- faiss_defuse-0.1.1/tests/test_convert.py +133 -0
- faiss_defuse-0.1.1/tests/test_core_stdlib_only.py +45 -0
- faiss_defuse-0.1.1/tests/test_decode.py +67 -0
- faiss_defuse-0.1.1/tests/test_fuzz.py +50 -0
- faiss_defuse-0.1.1/tests/test_header.py +97 -0
- faiss_defuse-0.1.1/tests/test_i18n.py +158 -0
- faiss_defuse-0.1.1/tests/test_jsontags.py +108 -0
- faiss_defuse-0.1.1/tests/test_loader.py +133 -0
- faiss_defuse-0.1.1/tests/test_scan.py +146 -0
- faiss_defuse-0.1.1/tests/test_verify.py +87 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
.venv/
|
|
5
|
+
.pytest_cache/
|
|
6
|
+
.ruff_cache/
|
|
7
|
+
.mypy_cache/
|
|
8
|
+
*.egg-info/
|
|
9
|
+
|
|
10
|
+
# Node
|
|
11
|
+
node_modules/
|
|
12
|
+
dist/
|
|
13
|
+
.next/
|
|
14
|
+
|
|
15
|
+
# 실행 산출물·모델·데이터 캐시
|
|
16
|
+
runs/
|
|
17
|
+
outputs/
|
|
18
|
+
.cache/
|
|
19
|
+
*.safetensors
|
|
20
|
+
*.gguf
|
|
21
|
+
*.bin
|
|
22
|
+
|
|
23
|
+
# 환경·비밀
|
|
24
|
+
.env
|
|
25
|
+
.env.*
|
|
26
|
+
!.env.example
|
|
27
|
+
|
|
28
|
+
# OS·에디터
|
|
29
|
+
.DS_Store
|
|
30
|
+
.vscode/
|
|
31
|
+
.idea/
|
|
32
|
+
|
|
33
|
+
# Flutter·Dart
|
|
34
|
+
.dart_tool/
|
|
35
|
+
build/
|
|
36
|
+
.flutter-plugins
|
|
37
|
+
.flutter-plugins-dependencies
|
|
38
|
+
coverage/
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here.
|
|
4
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
5
|
+
|
|
6
|
+
## [0.1.1] - 2026-11-22
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
- CI: use Node 24-based action versions, restrict workflow token to read-only, run the demo with `--lang en`, and add a core-install check (wheel without extras).
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
## [0.1.0] - 2026-11-22
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
- `scan`: static opcode scan of `index.pkl` (`pickletools.genops` plus a symbolic stack that follows memoised strings), allow-list verdicts `safe` / `unsafe` / `unsupported`, byte offsets for every finding, size and opcode limits.
|
|
16
|
+
- Inert decoder that never imports LangChain: allowed globals map to stubs or to small value shims (sets, dates, numpy scalars).
|
|
17
|
+
- `read_faiss_header`: validates the `index.faiss` header with the standard library before `faiss.read_index` is called.
|
|
18
|
+
- `inspect`, `convert`, `save_safe`: pickle-free `faiss-defuse/1` format (`index.faiss` + `docstore.jsonl` + `manifest.json` with SHA-256 hashes and FAISS options).
|
|
19
|
+
- `load_safe`: flag-free loader for pickle-free stores and for original `save_local` directories.
|
|
20
|
+
- `verify`: hashes, content and top-k equivalence against the original; optional `--trust-original` comparison.
|
|
21
|
+
- CLI `faiss-defuse scan|inspect|convert|verify|demo` with `--json`, exit codes, and English / Korean output (`--lang`, `FAISS_DEFUSE_LANG`, `LC_ALL` / `LC_MESSAGES` / `LANG`).
|
|
22
|
+
- `Limits.max_doc_nodes` (100,000 per document) and `Limits.max_total_nodes` (10,000,000 per store); `Limits.max_docstore_bytes` also bounds the JSON written by `convert` / `save_safe`.
|
|
23
|
+
- CLI `--limit NAME=NUMBER` (repeatable) on `scan`, `inspect`, `convert` and `verify` to change any `Limits` field; `limit-exceeded` errors say which flag raises the limit.
|
|
24
|
+
|
|
25
|
+
### Security
|
|
26
|
+
- Memo-reference amplification is bounded: a tiny pickle that reuses one object through many memo references fails fast with `limit-exceeded` instead of expanding to gigabytes. Allow-listed constructors that copy their argument (`set`, `frozenset`, `OrderedDict`, `_codecs.encode`) are capped at twice the pickle size (`reference-amplification`), and shared metadata is counted per document against `Limits.max_total_nodes`.
|
|
27
|
+
- An integer with more digits than Python can turn into text (4,300 by default) is reported as an unsupported value type (exit 1) instead of a raw `ValueError`.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LeeGyeongPil
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: faiss-defuse
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Inspect, convert and load LangChain FAISS stores without executing pickle: static scan, pickle-free format, flag-free loader.
|
|
5
|
+
Project-URL: Homepage, https://github.com/LeeGyeongPil/faiss-defuse
|
|
6
|
+
Project-URL: Issues, https://github.com/LeeGyeongPil/faiss-defuse/issues
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: deserialization,faiss,langchain,pickle,rag,security
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Security
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Provides-Extra: langchain
|
|
21
|
+
Requires-Dist: faiss-cpu<2,>=1.16.0; extra == 'langchain'
|
|
22
|
+
Requires-Dist: langchain-community<0.5,>=0.4.2; extra == 'langchain'
|
|
23
|
+
Requires-Dist: langchain-core<2,>=1.8.4; extra == 'langchain'
|
|
24
|
+
Requires-Dist: numpy>=1.26; extra == 'langchain'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# faiss-defuse
|
|
28
|
+
|
|
29
|
+
**English** | [한국어](https://github.com/LeeGyeongPil/faiss-defuse/blob/v0.1.1/README.ko.md)
|
|
30
|
+
|
|
31
|
+
Check, convert and load LangChain FAISS stores (`index.faiss` + `index.pkl`) **without running the pickle** and without `allow_dangerous_deserialization=True`. A Python library and a small CLI. The core uses only the standard library.
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+
|
|
35
|
+
*The built-in demo scans a clean store, a booby-trapped store and an old-format store, converts one, and proves nothing was executed.*
|
|
36
|
+
|
|
37
|
+
## What it does
|
|
38
|
+
|
|
39
|
+
`FAISS.save_local()` writes two files: `index.faiss` (the vectors) and `index.pkl` (your documents, as a Python pickle). `FAISS.load_local()` refuses to read the pickle unless you pass `allow_dangerous_deserialization=True`, and the usual advice is "only load files you made yourself". That is hard to follow when stores are downloaded, shared between teams or shipped in an image.
|
|
40
|
+
|
|
41
|
+
faiss-defuse gives you five things instead:
|
|
42
|
+
|
|
43
|
+
| Step | What it does | Needs FAISS? |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| `scan` | Reads the pickle's instructions without running them and says `safe` or `unsafe`, with the byte offset of each problem | no |
|
|
46
|
+
| `inspect` | Prints the `index.faiss` header (index type, dimension, vector count, metric), the document count and the metadata keys | no |
|
|
47
|
+
| `convert` / `save_safe` | Writes a pickle-free copy: `index.faiss` + `docstore.jsonl` + `manifest.json` (SHA-256 of both files) | `save_safe` only |
|
|
48
|
+
| `load_safe` | Returns a normal LangChain `FAISS` object, no flag needed | yes |
|
|
49
|
+
| `verify` | Checks hashes, then compares converted and original content and top-k search results | top-k part only |
|
|
50
|
+
|
|
51
|
+
Think of it as an X-ray machine plus a sealed box. The X-ray (`scan`) looks inside the parcel without opening it. The sealed box (the pickle-free format) is what you ship afterwards, with a tamper-evident sticker (the hashes).
|
|
52
|
+
|
|
53
|
+
## Why the flag is dangerous
|
|
54
|
+
|
|
55
|
+
A pickle is not data. It is a list of instructions for a small stack machine, and one instruction (`REDUCE`) can call any function it has imported. Here are the first instructions of the demo's booby-trapped `index.pkl` (from `pickletools.dis`, truncated; offsets depend on the payload):
|
|
56
|
+
|
|
57
|
+
```text
|
|
58
|
+
0: \x80 PROTO 4
|
|
59
|
+
2: \x95 FRAME 221
|
|
60
|
+
11: \x8c SHORT_BINUNICODE 'posix'
|
|
61
|
+
18: \x94 MEMOIZE (as 0)
|
|
62
|
+
19: \x8c SHORT_BINUNICODE 'system'
|
|
63
|
+
27: \x94 MEMOIZE (as 1)
|
|
64
|
+
28: \x93 STACK_GLOBAL
|
|
65
|
+
29: \x94 MEMOIZE (as 2)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`STACK_GLOBAL` at offset 28 imports `posix.system` (the `os.system` of Linux and macOS). A later `REDUCE` calls it. `load_local(..., allow_dangerous_deserialization=True)` would run that call as the file loads. The demo's payload is harmless (`echo` creating a marker file), and the demo shows the marker is never created.
|
|
69
|
+
|
|
70
|
+
## Install
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
uv add "faiss-defuse[langchain] @ git+https://github.com/LeeGyeongPil/faiss-defuse"
|
|
74
|
+
# or, from a clone:
|
|
75
|
+
git clone https://github.com/LeeGyeongPil/faiss-defuse && cd faiss-defuse && uv sync
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Python 3.11 or newer. No runtime dependencies for `scan`, `inspect` and `convert`. The `[langchain]` extra adds `langchain-community`, `langchain-core`, `faiss-cpu` and `numpy` for `load_safe`, `save_safe` and the top-k check. Install uv with `curl -LsSf https://astral.sh/uv/install.sh | sh` if you do not have it (a minimal Linux image also needs `git` and `curl`).
|
|
79
|
+
|
|
80
|
+
## Quick start (about a minute)
|
|
81
|
+
|
|
82
|
+
From a clone, with `uv sync` done:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
uv run faiss-defuse demo --out /tmp/faiss-defuse-demo
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```text
|
|
89
|
+
Practice mode: real scans on real files, but the embeddings are fake and deterministic (search quality is meaningless).
|
|
90
|
+
clean: SAFE
|
|
91
|
+
malicious: UNSAFE
|
|
92
|
+
legacy: SAFE
|
|
93
|
+
converted: VERIFIED
|
|
94
|
+
offset 0x1c STACK_GLOBAL posix.system (disallowed-global) - import outside the allow-list
|
|
95
|
+
sentinel file: not created - nothing was executed
|
|
96
|
+
samples written to /tmp/faiss-defuse-demo
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
**Practice data.** The demo builds its stores offline with fake, hash-based embeddings, so no model or API key is needed and search quality is meaningless. The scans, the conversion and the verification are real, run on real files. Real stores differ only in having real embeddings.
|
|
100
|
+
|
|
101
|
+
Now scan your own store (a directory made by `save_local`):
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
uv run faiss-defuse scan path/to/your_index_dir
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Run it on the demo's booby-trapped store to see a rejection (exit code 1):
|
|
108
|
+
|
|
109
|
+

|
|
110
|
+
|
|
111
|
+
*`scan` names the finding (`disallowed-global`), the opcode, the offset and the import. Nothing was executed.*
|
|
112
|
+
|
|
113
|
+
## Step by step
|
|
114
|
+
|
|
115
|
+
1. **Scan** the store you were given. The demo's clean store:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
uv run faiss-defuse scan /tmp/faiss-defuse-demo/clean
|
|
119
|
+
```
|
|
120
|
+
```text
|
|
121
|
+
SAFE index.pkl imports: datetime.date, InMemoryDocstore, Document protocol 4 783 opcodes 2,233 bytes
|
|
122
|
+
Nothing was executed.
|
|
123
|
+
```
|
|
124
|
+
`safe` means the pickle imports only the names a LangChain FAISS store uses (see [limits](#how-the-checks-work)). Everything else is rejected, not just "known bad" names.
|
|
125
|
+
|
|
126
|
+
2. **Inspect** it. This works without FAISS installed and also reads old stores whose pickles use the former `langchain.*` module paths:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
uv run faiss-defuse inspect /tmp/faiss-defuse-demo/legacy
|
|
130
|
+
```
|
|
131
|
+
```text
|
|
132
|
+
index.faiss IndexFlatL2 (IxF2) d=32 ntotal=12 metric=L2
|
|
133
|
+
index.pkl SAFE protocol 4 imports: datetime.date, InMemoryDocstore, Document
|
|
134
|
+
documents 12 (orphans: 0)
|
|
135
|
+
mapping OK (ntotal matches the id map)
|
|
136
|
+
metadata keys date 12, page 12, source 12, tags 12
|
|
137
|
+
module paths legacy
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+

|
|
141
|
+
|
|
142
|
+
*Header facts come from reading the first bytes of `index.faiss` with the standard library, before FAISS touches the file.*
|
|
143
|
+
|
|
144
|
+
3. **Convert** and **verify**:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
uv run faiss-defuse convert /tmp/faiss-defuse-demo/clean /tmp/faiss-defuse-demo/c2 --overwrite
|
|
148
|
+
uv run faiss-defuse verify /tmp/faiss-defuse-demo/c2 --against /tmp/faiss-defuse-demo/clean
|
|
149
|
+
```
|
|
150
|
+
```text
|
|
151
|
+
Converted 12 documents -> /tmp/faiss-defuse-demo/c2
|
|
152
|
+
options: distance_strategy=EUCLIDEAN_DISTANCE normalize_L2=False (source: inferred)
|
|
153
|
+
warning [normalize-l2-unknown]: normalize_L2 is not stored in the original pickle and cannot be inferred; assumed False. Pass normalize_l2=True (CLI: --normalize-l2) if the store was built with it.
|
|
154
|
+
warning [distance-strategy-inferred]: distance_strategy EUCLIDEAN_DISTANCE inferred from the index metric (L2)
|
|
155
|
+
VERIFIED 12/12 docs, top-5 equal for 12 probe vectors
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+

|
|
159
|
+
|
|
160
|
+
*LangChain does not save `normalize_L2` or the distance strategy in the pickle. If your store was built with `normalize_L2=True`, say so with `--normalize-l2`, otherwise scores can change silently. That is why the warning appears.*
|
|
161
|
+
|
|
162
|
+
4. **Load** it without any flag (see [Library](#library)).
|
|
163
|
+
|
|
164
|
+
## CLI
|
|
165
|
+
|
|
166
|
+
| Command | Purpose | Useful options |
|
|
167
|
+
|---|---|---|
|
|
168
|
+
| `faiss-defuse scan PATH` | Verdict without executing | `--json`, `--index-name`, `--limit` |
|
|
169
|
+
| `faiss-defuse inspect PATH` | Header, document count, mapping check, metadata keys | `--json`, `--limit` |
|
|
170
|
+
| `faiss-defuse convert SRC DST` | Pickle-free copy | `--normalize-l2`, `--distance-strategy`, `--overwrite`, `--json`, `--limit` |
|
|
171
|
+
| `faiss-defuse verify DIR` | Hashes; with `--against` also content and top-k | `--against ORIGINAL`, `--k`, `--probes`, `--trust-original`, `--json`, `--limit` |
|
|
172
|
+
| `faiss-defuse demo` | Offline sample stores and the whole flow (needs the `[langchain]` extra) | `--out DIR` |
|
|
173
|
+
|
|
174
|
+
Exit codes: `0` ok, `1` check failed (unsafe, unsupported content, mismatch), `2` usage error, `3` damaged, unreadable or over-limit input, `4` optional dependencies missing.
|
|
175
|
+
|
|
176
|
+
`--json` prints machine-readable output for CI. Keys and finding `code` values do not depend on the language; only `message` is translated. The clean store:
|
|
177
|
+
|
|
178
|
+

|
|
179
|
+
|
|
180
|
+
*(`opcode_counts` is trimmed in the screenshot.)*
|
|
181
|
+
|
|
182
|
+
`verify --trust-original` additionally loads the original with LangChain's own `load_local`. That **executes the original pickle**, so use it only on stores you built yourself. Plain `verify` never does.
|
|
183
|
+
|
|
184
|
+
**Display language.** `--lang en|ko`, or `FAISS_DEFUSE_LANG=en|ko`, then `LC_ALL` / `LC_MESSAGES` / `LANG`. Anything that is not Korean falls back to English. Korean output is shown in [README.ko.md](https://github.com/LeeGyeongPil/faiss-defuse/blob/v0.1.1/README.ko.md).
|
|
185
|
+
|
|
186
|
+
## Library
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
from faiss_defuse import load_safe, save_safe, scan
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
One-line change in an application:
|
|
193
|
+
|
|
194
|
+

|
|
195
|
+
|
|
196
|
+
*The same call, without the flag. `load_safe` accepts original `save_local` directories (scanned and decoded without running the pickle) and pickle-free stores (hashes checked first).*
|
|
197
|
+
|
|
198
|
+
A runnable example, [`examples/quickstart.py`](https://github.com/LeeGyeongPil/faiss-defuse/blob/v0.1.1/examples/quickstart.py) (it uses a fake embedding class, so it works offline):
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
uv run python examples/quickstart.py
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
```text
|
|
205
|
+
scan: safe ['langchain_community.docstore.in_memory.InMemoryDocstore', 'langchain_core.documents.base.Document']
|
|
206
|
+
files: ['docstore.jsonl', 'index.faiss', 'manifest.json']
|
|
207
|
+
top hit: dogs bark {'n': 2}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
(`langchain-community` prints a `DeprecationWarning` on import because the package is no longer maintained; the output above was captured with `python -W ignore::DeprecationWarning`.)
|
|
211
|
+
|
|
212
|
+
### API
|
|
213
|
+
|
|
214
|
+
| Name | What it does | Main arguments | Returns / raises |
|
|
215
|
+
|---|---|---|---|
|
|
216
|
+
| `scan(path)` | Static verdict for a store directory or an `index.pkl` | `limits`, `index_name` | `ScanReport` (`verdict`, `imports`, `findings`) |
|
|
217
|
+
| `scan_bytes(data)` | Same for bytes in memory | `limits`, `source` | `ScanReport` |
|
|
218
|
+
| `read_faiss_header(path)` | Validates and parses the `index.faiss` header | | `FaissHeader` |
|
|
219
|
+
| `inspect(path)` | Header, document count, mapping and metadata summary | `index_name`, `limits` | `StoreInfo` |
|
|
220
|
+
| `convert(src, dst)` | Original store to pickle-free store | `distance_strategy`, `normalize_l2`, `overwrite`, `index_name` | `Manifest`; `UnsafePickleError`, `UnsupportedContentError`, `OutputExistsError` |
|
|
221
|
+
| `save_safe(vectorstore, dst)` | Save a live LangChain `FAISS` object pickle-free (records the real options) | `overwrite` | `Manifest`; needs the extra |
|
|
222
|
+
| `load_safe(path, embeddings)` | Load without the flag | `distance_strategy`, `normalize_l2`, `allow_option_override`, `index_name` | LangChain `FAISS`; `ManifestMismatchError`, `MalformedStoreError`, `OptionConflictError`, `UnsafePickleError` |
|
|
223
|
+
| `verify(converted)` | Hash, header, mapping checks; with `original=` also content and top-k | `original`, `trust_original`, `k`, `probes` | `VerifyReport` |
|
|
224
|
+
| `Limits` | Size, opcode, node and depth limits for hostile input (see [resource limits](#resource-limits)) | `max_doc_nodes=...` and the other fields | dataclass |
|
|
225
|
+
|
|
226
|
+
All errors derive from `DefuseError` (also `MissingExtraError` when the extra is not installed).
|
|
227
|
+
|
|
228
|
+
## CI recipe
|
|
229
|
+
|
|
230
|
+
Build step, after creating the index:
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
save_safe(store, "dist/index_store", overwrite=True)
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Before publishing the artifact (this step compares against the original and fails the job on mismatch):
|
|
237
|
+
|
|
238
|
+
```bash
|
|
239
|
+
faiss-defuse scan build/index_dir # exit 1 if the pickle is not safe
|
|
240
|
+
faiss-defuse verify dist/index_store --against build/index_dir
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
In the serving app, `load_safe("dist/index_store", embeddings)`. A hash mismatch raises `ManifestMismatchError` before the file reaches FAISS. The hashes stop tampering *in transit*; they cannot stop someone who rewrites the files and the manifest together. `verify --against` catches that by comparing with the original.
|
|
244
|
+
|
|
245
|
+
## The pickle-free format
|
|
246
|
+
|
|
247
|
+
Three files: `index.faiss` (unchanged), `docstore.jsonl` (one document per line, with type tags such as `{"$tuple": [...]}` and `{"$date": "2025-01-01"}` for values JSON lacks), and `manifest.json` (format version, SHA-256 and size of both files, index facts, FAISS options). Details and the full tag table are in [docs/format.md](https://github.com/LeeGyeongPil/faiss-defuse/blob/v0.1.1/docs/format.md).
|
|
248
|
+
|
|
249
|
+
## How the checks work
|
|
250
|
+
|
|
251
|
+
Two gates, in order:
|
|
252
|
+
|
|
253
|
+
1. **Static scan.** `pickletools.genops` reads the opcodes. A symbolic stack follows strings through `MEMOIZE`/`BINGET`, so `builtins.eval` hidden behind a memo reference is still seen. Only an exact allow-list of `(module, name)` pairs passes. Trailing data after `STOP`, extension codes, persistent ids and dotted names are rejected.
|
|
254
|
+
2. **Inert decoder.** Only after a pass, a decoder rebuilds `(id, page_content, metadata)` from the instructions using stub classes. It never imports LangChain, so a safe verdict does not depend on what LangChain's classes expose. Restricted unpicklers that return real allowed classes can be bypassed through attributes those classes expose, so this library does not use one.
|
|
255
|
+
|
|
256
|
+
`index.faiss` is also input: the header (known `fourcc`, plausible `d` and `ntotal`, file size matching the vector count for flat indexes) is checked with `struct` **before** `faiss.read_index` is called. Supported index kinds: `IxF2 IxFI IxFl IHNf IwFl IxMp IxM2 IxPq`. `docstore.jsonl` is checked against the manifest and the vector count.
|
|
257
|
+
|
|
258
|
+
### Resource limits
|
|
259
|
+
|
|
260
|
+
A tiny hostile pickle can ask for a lot of work, because a pickle reference reuses an object instead of copying it. Every limit is checked **before** the memory is allocated or the bytes are written. Defaults:
|
|
261
|
+
|
|
262
|
+
| Limit | Default | What it bounds |
|
|
263
|
+
|---|---|---|
|
|
264
|
+
| `max_pickle_bytes` | 512 MiB | size of `index.pkl` |
|
|
265
|
+
| `max_opcodes` | 50,000,000 | opcodes the scan reads |
|
|
266
|
+
| `max_string_bytes` | 64 MiB | one string in the pickle |
|
|
267
|
+
| `max_faiss_bytes` | 16 GiB | size of `index.faiss` |
|
|
268
|
+
| `max_vectors` | 200,000,000 | `ntotal` in the index header |
|
|
269
|
+
| `max_docstore_bytes` | 2 GiB | `docstore.jsonl`, both when read and when written by `convert` |
|
|
270
|
+
| `max_findings` | 200 | findings listed in one report |
|
|
271
|
+
| `max_depth` | 100 | nesting depth |
|
|
272
|
+
| `max_doc_nodes` | 100,000 | values in one document's metadata, shared references counted each time |
|
|
273
|
+
| `max_total_nodes` | 10,000,000 | values in the whole store |
|
|
274
|
+
|
|
275
|
+
Going over a limit stops with `limit-exceeded` (exit 3 for `convert`, `inspect` and `verify`; `scan` reports `UNSAFE` with that finding). A second limit cannot be changed: while decoding, the data copied by constructors such as `frozenset(...)` may not exceed twice the pickle size plus 64 KiB. Beyond that the store is refused as `reference-amplification` (exit 3), because an honest pickle writes its constructor arguments out instead of reusing them. Integers with more than 4,300 digits are reported as `unsupported` (exit 1).
|
|
276
|
+
|
|
277
|
+
A big but honest store can raise a limit, from the command line or in Python:
|
|
278
|
+
|
|
279
|
+
```bash
|
|
280
|
+
faiss-defuse convert SRC DST --limit max_doc_nodes=500000 --limit max_docstore_bytes=8000000000
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
```python
|
|
284
|
+
convert(src, dst, limits=Limits(max_doc_nodes=500_000))
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`--limit NAME=NUMBER` can be repeated and works on `scan`, `inspect`, `convert` and `verify`. A bad value is a usage error (exit 2). If `convert` fails, it removes the destination folder it created.
|
|
288
|
+
|
|
289
|
+
### What it does not guarantee
|
|
290
|
+
|
|
291
|
+
- FAISS's own parser is not sandboxed. Header and size checks, the hashes and a lower bound of `faiss-cpu>=1.16.0` reduce the risk from a crafted `index.faiss`; they do not remove it. An isolated read is planned.
|
|
292
|
+
- A `safe` verdict is about the pickle only, not about the text in your documents. `scan` decides whether code could run; it does not decode the store, so a pickle built to waste memory can still print `SAFE`. Such stores are stopped later, by the limits above, in `convert`, `inspect`, `verify` and `load_safe`. Within the default limits a small pickle can still make `convert` write up to `max_docstore_bytes` (2 GiB) to disk, with memory use kept small.
|
|
293
|
+
- Not supported yet (reported as `unsupported`, not as unsafe, exit 1): `serialize_to_bytes()` output, Annoy and ScaNN stores, numpy-array and pandas `Timestamp` metadata.
|
|
294
|
+
- The scan is pure Python: about 2.7 s for a 100,000-document store (20.8 MB `index.pkl`) on the author's laptop; convert 3.7 s, `load_safe` of a converted store 0.7 s.
|
|
295
|
+
|
|
296
|
+
## When to use it
|
|
297
|
+
|
|
298
|
+
- You receive, download or ship LangChain FAISS stores and want to stop enabling `allow_dangerous_deserialization`.
|
|
299
|
+
- You want a CI gate and a reproducible, hash-checked artifact for an index.
|
|
300
|
+
- Other tools: for generic pickle files (not LangChain-specific) see [fickling](https://github.com/trailofbits/fickling) and [picklescan](https://github.com/mmaitre314/picklescan); for model weights prefer [safetensors](https://github.com/huggingface/safetensors). faiss-defuse knows only the LangChain FAISS layout and rejects anything else.
|
|
301
|
+
|
|
302
|
+
## Troubleshooting
|
|
303
|
+
|
|
304
|
+
| Symptom | Cause | Fix |
|
|
305
|
+
|---|---|---|
|
|
306
|
+
| `error: optional dependencies missing: ...` (exit 4) | `load_safe`, `save_safe` or top-k need the extra | install `faiss-defuse[langchain]` |
|
|
307
|
+
| `UNSAFE ... disallowed-global` on your own store | the pickle imports something outside the allow-list (a custom metadata class, for example) | do not enable the flag; rebuild the store with plain-value metadata |
|
|
308
|
+
| `limit-exceeded` or `reference-amplification`, exit 3 | the file is larger than a limit, or built so that decoding would multiply its size | check where the store came from; if it is yours and large, pass `--limit NAME=NUMBER` (`reference-amplification` cannot be raised) |
|
|
309
|
+
| `unsupported-value-type`, exit 1 | metadata holds numpy arrays or pandas values | convert them to plain Python values and rebuild |
|
|
310
|
+
| `MISMATCH ... does not match manifest.json` | a file changed after it was written | rebuild with `faiss-defuse convert` from the original |
|
|
311
|
+
| scores differ after switching | `normalize_L2` was not recorded | `convert --normalize-l2` or `load_safe(..., normalize_l2=True)` |
|
|
312
|
+
|
|
313
|
+
## Versions and compatibility
|
|
314
|
+
|
|
315
|
+
Semantic Versioning. During 0.x, minor versions may change the API; see [CHANGELOG.md](https://github.com/LeeGyeongPil/faiss-defuse/blob/v0.1.1/CHANGELOG.md). Tested with Python 3.11, 3.12, 3.13, `langchain-community` 0.4.2, `langchain-core` 1.8.4, `faiss-cpu` 1.16.0, `numpy` 2.5.5. LangChain has archived `langchain-community`; this library keeps the stub decoder independent of it and the `[langchain]` extra is capped below 0.5.
|
|
316
|
+
|
|
317
|
+
## Development
|
|
318
|
+
|
|
319
|
+
```bash
|
|
320
|
+
uv sync
|
|
321
|
+
uv run pytest -q
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
## Sources (checked 2026-11-22)
|
|
325
|
+
|
|
326
|
+
- LangChain `FAISS.load_local`: https://reference.langchain.com/python/langchain-community/vectorstores/faiss/FAISS/load_local
|
|
327
|
+
- `langchain-community` sunset notice: https://github.com/langchain-ai/langchain-community/issues/674
|
|
328
|
+
- Python `pickletools`: https://docs.python.org/3/library/pickletools.html
|
|
329
|
+
- Hugging Face on pickle risks: https://huggingface.co/docs/hub/security-pickle
|
|
330
|
+
- CVE-2024-5998 (a deserialization vulnerability in FAISS loading): https://nvd.nist.gov/vuln/detail/CVE-2024-5998
|
|
331
|
+
|
|
332
|
+
## License
|
|
333
|
+
|
|
334
|
+
MIT.
|