From ec842cf7ba13919efb690f04cc0c48a7bc0476c1 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Sun, 15 Nov 2026 23:54:04 +0800 Subject: [PATCH] fix(python): stop pickle protocols 0 and 1 from aborting the interpreter pickle.dumps(obj, protocol=0) or protocol=1 on any rabitqlib object aborted the process. Those protocols reduce through copyreg._reduce_ex, which calls pybind11_object(obj); its constructor throws a C++ exception through the C API, so the interpreter terminates (pybind11 issue 3745, reproduced with pybind11 3.1.0 and master). Every extension class and enum now defines __reduce_ex__, which uses the protocol-2 reduction for protocols 0 and 1. quant.Rotator, quant.Query and the enums pickle with every protocol; the other classes raise TypeError, as they already did with protocol 2 and higher. Protocols 2 to 5 produce the same bytes as before. A child-process test covers protocols 0 and 1 on every class, and a static test checks that each extension class defines __reduce_ex__. --- docs/docs/releases/unreleased.md | 1 + python_bindings/bindings_common.hpp | 14 ++++ python_bindings/hnsw_bindings.cpp | 6 ++ python_bindings/ivf_bindings.cpp | 6 ++ python_bindings/kmeans_bindings.cpp | 21 ++++- python_bindings/quant_bindings.cpp | 12 +++ python_bindings/rabitq_bindings.cpp | 13 +++ python_bindings/symqg_bindings.cpp | 6 ++ tests/python/test_pickle_protocols.py | 112 ++++++++++++++++++++++++++ 9 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 tests/python/test_pickle_protocols.py diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index 1da1577f..4ffe7c67 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -62,6 +62,7 @@ - Errors in an HNSW routing graph name the graph rather than the sidecar: `Truncated HNSW centroid graph` and `HNSW centroid graph changed while loading` replace their `sidecar` forms. - A missing sidecar of an earlier file still raises `Cannot open HNSW centroid sidecar`. - A failed HNSW-RaBitQ write raises `HNSW index file cannot be written` instead of `HNSW failed to write index file`. +- `pickle.dumps(obj, protocol=0)` or `protocol=1` on a `rabitqlib` object no longer aborts the Python process. `quant.Rotator` and `quant.Query` now pickle with every protocol; the index, k-means, parameter and iteration-statistics classes raise `TypeError: cannot pickle ...`, as they already did with protocol 2 and higher, which include the default. Protocols 0 and 1 cannot reduce pybind11 objects ([pybind11#3745](https://github.com/pybind/pybind11/issues/3745)), so they now use the protocol-2 reduction. ## C++ changes diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp index d17d98c0..1ffbcaf5 100644 --- a/python_bindings/bindings_common.hpp +++ b/python_bindings/bindings_common.hpp @@ -72,6 +72,20 @@ class IndexAccess { [[nodiscard]] Guard write() { return Guard(*this, true); } }; +// `__reduce_ex__` for every extension class and enum. Pickle protocols 0 and 1 reduce +// through copyreg._reduce_ex, which calls pybind11_object(self); that constructor throws a +// C++ exception through the C API and aborts the interpreter (pybind11 issue 3745). +// Reducing with protocol 2 instead pickles a class that defines py::pickle with any +// protocol and raises TypeError for the others, as protocol 2 already does. +inline py::object reduce_ex_with_protocol_2(const py::object& self, int protocol) { + const auto object_type = + py::reinterpret_borrow(reinterpret_cast(&PyBaseObject_Type)); + return object_type.attr("__reduce_ex__")(self, std::max(protocol, 2)); +} + +inline constexpr const char* kReduceExDoc = + "Reduce for pickle; protocols 0 and 1 use the protocol-2 reduction."; + // Resolve Python callbacks before index guards and own bytes across GIL release. inline std::string path_string(py::handle value) { // The old std::string caster also accepted bytearray directly. diff --git a/python_bindings/hnsw_bindings.cpp b/python_bindings/hnsw_bindings.cpp index 9b41b6d2..17b8ad3c 100644 --- a/python_bindings/hnsw_bindings.cpp +++ b/python_bindings/hnsw_bindings.cpp @@ -473,6 +473,12 @@ link through the stored codes, so add most vectors in the first call. Capacity grows geometrically when needed. Removed IDs are not reused.)doc"; py::class_(m, "HnswIndex", kIndexDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init< size_t, diff --git a/python_bindings/ivf_bindings.cpp b/python_bindings/ivf_bindings.cpp index 2f95616c..2f099f42 100644 --- a/python_bindings/ivf_bindings.cpp +++ b/python_bindings/ivf_bindings.cpp @@ -361,6 +361,12 @@ untrained and empty. Batch additions to reduce repeated cluster copying; reserve_cluster can preallocate room.)doc"; py::class_(m, "IvfIndex", kIndexDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init< size_t, diff --git a/python_bindings/kmeans_bindings.cpp b/python_bindings/kmeans_bindings.cpp index 79cca9b2..7e7960b6 100644 --- a/python_bindings/kmeans_bindings.cpp +++ b/python_bindings/kmeans_bindings.cpp @@ -73,7 +73,14 @@ py::tuple assign(const Clustering& clustering, py::handle x) { template void bind_training_parameters(py::class_& binding) { - binding.def(py::init<>(), "Create parameters with their documented defaults.") + binding + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) + .def(py::init<>(), "Create parameters with their documented defaults.") .def_readwrite( "niter", &Parameters::niter, @@ -138,6 +145,12 @@ void bind_training_parameters(py::class_& binding) { template void bind_clustering(py::module_& m, const char* native_name, const char* public_name) { py::class_(m, native_name) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def(py::init()) .def("train", &train, py::arg("x")) .def("assign", &assign, py::arg("x")) @@ -240,6 +253,12 @@ on RaBitQKMeans.)doc" "KMeansIterationStats", R"doc(Read-only statistics for one completed clustering iteration.)doc" ) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def_readonly( "iteration", &KMeansIterationStats::iteration, diff --git a/python_bindings/quant_bindings.cpp b/python_bindings/quant_bindings.cpp index b1b3a551..8f91198d 100644 --- a/python_bindings/quant_bindings.cpp +++ b/python_bindings/quant_bindings.cpp @@ -2058,6 +2058,12 @@ Examples (2, 128))doc"; py::class_(quant, "Rotator", kRotatorDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init(), py::arg("dim"), @@ -2276,6 +2282,12 @@ num_threads : int, optional OMP_NUM_THREADS.)doc"; py::class_(quant, "Query", kQueryDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init(&QuantQuery::create), py::arg("rotated_query"), diff --git a/python_bindings/rabitq_bindings.cpp b/python_bindings/rabitq_bindings.cpp index bb4984fb..55d2f187 100644 --- a/python_bindings/rabitq_bindings.cpp +++ b/python_bindings/rabitq_bindings.cpp @@ -1,6 +1,7 @@ #include #include +#include "bindings_common.hpp" #include "rabitqlib/core/metric.hpp" #include "rabitqlib/core/rotator.hpp" #include "rabitqlib/index/format_error.hpp" @@ -60,11 +61,23 @@ PYBIND11_MODULE(_rabitqlib, m) { // Register shared enums once py::enum_(m, "MetricType") + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .value("L2", rabitqlib::METRIC_L2) .value("IP", rabitqlib::METRIC_IP) .export_values(); py::enum_(m, "RotatorType") + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .value("FhtKacRotator", rabitqlib::RotatorType::FhtKacRotator) .value("MatrixRotator", rabitqlib::RotatorType::MatrixRotator) .export_values(); diff --git a/python_bindings/symqg_bindings.cpp b/python_bindings/symqg_bindings.cpp index 3ddd9244..c941dc71 100644 --- a/python_bindings/symqg_bindings.cpp +++ b/python_bindings/symqg_bindings.cpp @@ -376,6 +376,12 @@ np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers.)doc"; py::class_(m, "SymqgIndex", kIndexDoc) + .def( + "__reduce_ex__", + &rabitqlib::python_bindings::reduce_ex_with_protocol_2, + py::arg("protocol"), + rabitqlib::python_bindings::kReduceExDoc + ) .def( py::init< size_t, diff --git a/tests/python/test_pickle_protocols.py b/tests/python/test_pickle_protocols.py new file mode 100644 index 00000000..3fb271e0 --- /dev/null +++ b/tests/python/test_pickle_protocols.py @@ -0,0 +1,112 @@ +"""Pickle protocols 0 and 1 raise or round-trip instead of aborting the interpreter. + +Those protocols reduce through copyreg, which calls the constructor of pybind11's base +class; that throws through the C API and aborts the process (pybind11 issue 3745) +unless the class defines __reduce_ex__. The calls therefore run in a child process. +""" + +import subprocess +import sys +import textwrap + +import rabitqlib +from rabitqlib import _rabitqlib + +CHILD = textwrap.dedent( + """ + import pickle + import sys + + import numpy as np + import rabitqlib + from rabitqlib import _rabitqlib, quant + + if rabitqlib.__file__ != sys.argv[1]: + raise SystemExit(f"child imported {rabitqlib.__file__}, not {sys.argv[1]}") + x = np.random.default_rng(0).normal(size=(64, 64)).astype(np.float32) + flat = rabitqlib.RaBitQKMeans(64, 2, niter=1, num_threads=1, seed=1) + flat.train(x) + graph = rabitqlib.QGKMeans(64, 33, niter=1, num_threads=1, seed=1) + graph.train(x) + + def state(value): + return pickle.dumps(value, protocol=2) + + picklable = { + "Rotator": quant.Rotator(64, seed=1), + "Query": quant.Query(x[0], metric="ip"), + "Query with centroid": quant.Query(x[0], metric="l2", centroid=x[1]), + "MetricType": _rabitqlib.MetricType.IP, + "RotatorType": _rabitqlib.RotatorType.FhtKacRotator, + } + unpicklable = { + "IvfIndex": rabitqlib.IvfIndex(64, 2, seed=1), + "HnswIndex": rabitqlib.HnswIndex(64, seed=1), + "SymqgIndex": rabitqlib.SymqgIndex(64, seed=1), + "QGKMeansParameters": rabitqlib.QGKMeansParameters(), + "RaBitQKMeansParameters": rabitqlib.RaBitQKMeansParameters(), + "KMeansIterationStats": flat.iteration_stats[0], + "_RaBitQKMeans": flat._impl, + "_QGKMeans": graph._impl, + "RaBitQKMeans": flat, + } + for protocol in (0, 1): + for name, value in picklable.items(): + copy = pickle.loads(pickle.dumps(value, protocol=protocol)) + if state(copy) != state(value): + raise SystemExit(f"{name} changed in a protocol {protocol} round trip") + print(name, protocol, "round-trip", flush=True) + for name, value in unpicklable.items(): + try: + pickle.dumps(value, protocol=protocol) + except TypeError as error: + if "cannot pickle" not in str(error): + raise SystemExit(f"{name}: {error}") + print(name, protocol, "TypeError", flush=True) + else: + raise SystemExit(f"{name} pickled with protocol {protocol}") + print(len(picklable) + len(unpicklable), "cases", flush=True) + """ +) + + +def test_old_protocols_round_trip_or_raise_in_a_child_process(): + result = subprocess.run( + [sys.executable, "-c", CHILD, rabitqlib.__file__], + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stdout + result.stderr + lines = result.stdout.splitlines() + cases = int(lines[-1].split()[0]) + assert len(lines) == 1 + 2 * cases, lines + assert "Query with centroid 0 round-trip" in lines + assert "_QGKMeans 1 TypeError" in lines + + +def extension_classes(): + """Every pybind11 class that rabitqlib registered, found through the subclass tree.""" + pending = [ + base + for base in type(_rabitqlib.MetricType.IP).__mro__ + if base.__name__ == "pybind11_object" + ] + found = [] + while pending: + cls = pending.pop() + pending.extend(cls.__subclasses__()) + # quant.py renames its classes' module to rabitqlib.quant when imported. + if cls.__module__.split(".")[0] == "rabitqlib": + found.append(cls) + return found + + +def test_every_extension_class_defines_reduce_ex(): + classes = extension_classes() + names = {cls.__name__ for cls in classes} + assert {"IvfIndex", "Query", "_QGKMeans", "MetricType"} <= names, names + assert ( + sorted(cls.__name__ for cls in classes if "__reduce_ex__" not in vars(cls)) + == [] + )