Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PyOV] Safeguard `ConstOutput`'s `RTMap` from mutation (#37203)

Przemyslaw Wysocki402a000e6c7f
diff --git a/src/bindings/python/src/pyopenvino/graph/node_output.cpp b/src/bindings/python/src/pyopenvino/graph/node_output.cpp
index 8b6fe5197a0..c92bf349b16 100644
--- a/src/bindings/python/src/pyopenvino/graph/node_output.cpp
+++ b/src/bindings/python/src/pyopenvino/graph/node_output.cpp
@@ -15,16 +15,120 @@ namespace py = pybind11;
template void regclass_graph_Output<ov::Node>(py::module m, std::string typestring);
template void regclass_graph_Output<const ov::Node>(py::module m, std::string typestring);
+void regclass_graph_ConstOutputRTMap(py::module m) {
+ auto warn = []() {
+ Common::utils::deprecation_warning("Setting rt_info via ConstOutput",
+ "2027.0",
+ "Use a non-const output to modify runtime info.");
+ };
+
+ py::class_<ConstRTMapView, ov::RTMap>(m, "_ConstRTMapView")
+ // mutating: warn then delegate to the real map
+ .def("__setitem__",
+ [warn](ConstRTMapView& self, const std::string& k, const std::string& v) {
+ warn();
+ (*self.actual)[k] = v;
+ })
+ .def("__setitem__",
+ [warn](ConstRTMapView& self, const std::string& k, int64_t v) {
+ warn();
+ (*self.actual)[k] = v;
+ })
+ .def("__delitem__",
+ [warn](ConstRTMapView& self, const std::string& k) {
+ warn();
+ auto it = self.actual->find(k);
+ if (it == self.actual->end())
+ throw py::key_error(k);
+ self.actual->erase(it);
+ })
+ // read-only: delegate without warning
+ .def("__getitem__",
+ [](ConstRTMapView& self, const std::string& k) -> py::object {
+ auto it = self.actual->find(k);
+ if (it == self.actual->end())
+ throw py::key_error(k);
+ return Common::utils::from_ov_any_no_leaves(it->second);
+ })
+ .def("__contains__",
+ [](const ConstRTMapView& self, const std::string& k) {
+ return self.actual->count(k) > 0;
+ })
+ .def("__len__",
+ [](const ConstRTMapView& self) {
+ return self.actual->size();
+ })
+ .def("__bool__",
+ [](const ConstRTMapView& self) {
+ return !self.actual->empty();
+ })
+ .def(
+ "__iter__",
+ [](ConstRTMapView& self) {
+ return py::make_key_iterator(self.actual->begin(), self.actual->end());
+ },
+ py::keep_alive<0, 1>())
+ .def(
+ "keys",
+ [](ConstRTMapView& self) {
+ return py::make_key_iterator(self.actual->begin(), self.actual->end());
+ },
+ py::keep_alive<0, 1>())
+ .def(
+ "items",
+ [](ConstRTMapView& self) -> py::object {
+ return py::cast(*self.actual, py::return_value_policy::reference).attr("items")();
+ },
+ py::keep_alive<0, 1>())
+ .def(
+ "values",
+ [](ConstRTMapView& self) -> py::object {
+ return py::cast(*self.actual, py::return_value_policy::reference).attr("values")();
+ },
+ py::keep_alive<0, 1>())
+ .def("__repr__", [](const ConstRTMapView& self) {
+ return std::string("<RTMap>");
+ });
+}
+
template <typename T>
void def_type_dependent_functions(py::class_<ov::Output<T>, std::shared_ptr<ov::Output<T>>>& output) {}
template <>
void def_type_dependent_functions<const ov::Node>(
- py::class_<ov::Output<const ov::Node>, std::shared_ptr<ov::Output<const ov::Node>>>& output) {}
+ py::class_<ov::Output<const ov::Node>, std::shared_ptr<ov::Output<const ov::Node>>>& output) {
+ auto getter = [](py::object self_obj) -> py::object {
+ ov::RTMap& rt = const_cast<ov::RTMap&>(self_obj.cast<ov::Output<const ov::Node>&>().get_rt_info());
+ return py::cast(std::make_unique<ConstRTMapView>(rt, self_obj));
+ };
+ output.def("get_rt_info",
+ getter,
+ R"(
+ Returns a view of the RTMap for this output.
+ Reads are transparent; writes are deprecated (to be removed in 2027.0).
+ Use a non-const output to modify runtime info.
+
+ :return: View of runtime info dictionary.
+ :rtype: openvino.RTMap
+ )");
+ output.def_property_readonly("rt_info", getter);
+}
template <>
void def_type_dependent_functions<ov::Node>(
py::class_<ov::Output<ov::Node>, std::shared_ptr<ov::Output<ov::Node>>>& output) {
+ output.def("get_rt_info",
+ (ov::RTMap & (ov::Output<ov::Node>::*)()) & ov::Output<ov::Node>::get_rt_info,
+ py::return_value_policy::reference_internal,
+ R"(
+ Returns RTMap which is a dictionary of user defined runtime info.
+
+ :return: A dictionary of user defined data.
+ :rtype: openvino.RTMap
+ )");
+ output.def_property_readonly("rt_info",
+ (ov::RTMap & (ov::Output<ov::Node>::*)()) & ov::Output<ov::Node>::get_rt_info,
+ py::return_value_policy::reference_internal);
output.def("set_names",
&ov::Output<ov::Node>::set_names,
py::arg("names"),
diff --git a/src/bindings/python/src/pyopenvino/graph/node_output.hpp b/src/bindings/python/src/pyopenvino/graph/node_output.hpp
index f7e519faaae..f205681c9e3 100644
--- a/src/bindings/python/src/pyopenvino/graph/node_output.hpp
+++ b/src/bindings/python/src/pyopenvino/graph/node_output.hpp
@@ -19,6 +19,21 @@ using PyRTMap = ov::Node::RTMap;
PYBIND11_MAKE_OPAQUE(PyRTMap);
+// \brief Pybind11 subclass of RTMap used as the return type of ConstOutput::get_rt_info().
+//
+// The C++ base is empty and is never used for data storage; all map operations
+// are forwarded through the `actual` pointer to the real tensor RTMap owned by the node.
+// Storing `owner` (the Python ConstOutput object) keeps the node alive.
+struct ConstRTMapView : public ov::RTMap {
+ ov::RTMap* actual; // non-owning pointer to the real RTMap
+ py::object owner; // Python ConstOutput that owns the node
+
+ ConstRTMapView(ov::RTMap& map, py::object owner_obj)
+ : ov::RTMap(), actual(&map), owner(std::move(owner_obj)) {}
+};
+
+void regclass_graph_ConstOutputRTMap(py::module m);
+
// this function is overloaded in the corresponding cpp file with T=ov::Node
// it exposes additional functions with T = ov::Node, which are undefined with T = const ov::Node
template<typename T>
@@ -142,15 +157,6 @@ void regclass_graph_Output(py::module m, std::string typestring)
:return: Tensor of the output.
:rtype: openvino._pyopenvino.DescriptorTensor
)");
- output.def("get_rt_info",
- (ov::RTMap & (ov::Output<VT>::*)()) & ov::Output<VT>::get_rt_info,
- py::return_value_policy::reference_internal,
- R"(
- Returns RTMap which is a dictionary of user defined runtime info.
-
- :return: A dictionary of user defined data.
- :rtype: openvino.RTMap
- )");
output.def("__repr__", [](const ov::Output<VT>& self) {
std::stringstream shape_type_ss;
@@ -169,14 +175,6 @@ void regclass_graph_Output(py::module m, std::string typestring)
output.def_property_readonly("partial_shape", &ov::Output<VT>::get_partial_shape, py::return_value_policy::copy);
output.def_property_readonly("target_inputs", &ov::Output<VT>::get_target_inputs);
output.def_property_readonly("tensor", &ov::Output<VT>::get_tensor);
- output.def_property_readonly("rt_info",
- (ov::RTMap&(ov::Output<VT>::*)()) &
- ov::Output<VT>::get_rt_info,
- py::return_value_policy::reference_internal);
- output.def_property_readonly("rt_info",
- (const ov::RTMap&(ov::Output<VT>::*)() const) &
- ov::Output<VT>::get_rt_info,
- py::return_value_policy::reference_internal);
// define functions available only for specific type
def_type_dependent_functions<VT>(output);
diff --git a/src/bindings/python/src/pyopenvino/pyopenvino.cpp b/src/bindings/python/src/pyopenvino/pyopenvino.cpp
index cb614a72d6f..7d2348b8b1f 100644
--- a/src/bindings/python/src/pyopenvino/pyopenvino.cpp
+++ b/src/bindings/python/src/pyopenvino/pyopenvino.cpp
@@ -236,6 +236,7 @@ PYBIND11_MODULE(_pyopenvino, m) {
regclass_graph_Input(m);
regclass_graph_Node(m);
regclass_graph_NodeFactory(m);
+ regclass_graph_ConstOutputRTMap(m);
regclass_graph_Output<const ov::Node>(m, std::string("Const"));
regmodule_graph_util(m);
regclass_graph_Op(m);
diff --git a/src/bindings/python/tests/test_graph/test_basic.py b/src/bindings/python/tests/test_graph/test_basic.py
index 07981db34e5..d33dbe398aa 100644
--- a/src/bindings/python/tests/test_graph/test_basic.py
+++ b/src/bindings/python/tests/test_graph/test_basic.py
@@ -13,6 +13,7 @@ from openvino import (
Model,
Layout,
PartialShape,
+ RTMap,
Shape,
Strides,
Tensor,
@@ -523,6 +524,48 @@ def test_runtime_info():
assert relu_node.rt_info["new_key"] == "new_value"
+def test_rt_info_const_output():
+ import warnings
+
+ param = ov.opset13.parameter(PartialShape([1, 3]), Type.f32, name="in")
+ relu = ov.opset13.relu(param)
+ model = Model([relu], [param], "test_rt_info_const_output")
+ core = ov.Core()
+ compiled = core.compile_model(model, "CPU")
+ co = compiled.outputs[0]
+
+ # Reading should not emit any warning
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ _ = co.get_rt_info()
+ _ = co.rt_info
+ rt = co.get_rt_info()
+ _ = list(rt)
+
+ with pytest.warns(DeprecationWarning, match="Setting rt_info via ConstOutput"):
+ co.get_rt_info()["dep_key"] = "dep_val"
+ assert "dep_key" in co.get_rt_info()
+
+ with pytest.warns(DeprecationWarning, match="Setting rt_info via ConstOutput"):
+ co.rt_info["dep_key2"] = "dep_val2"
+ assert "dep_key2" in co.rt_info
+
+ with pytest.warns(DeprecationWarning, match="Setting rt_info via ConstOutput"):
+ del co.rt_info["dep_key"]
+ assert "dep_key" not in co.rt_info
+
+ assert isinstance(co.get_rt_info(), RTMap)
+
+ rt = co.get_rt_info()
+ before_len = len(rt)
+ with pytest.raises(KeyError):
+ _ = rt["nonexistent_key"]
+ assert len(rt) == before_len, "__getitem__ must not insert a default value on missing keys"
+
+ with pytest.warns(DeprecationWarning, match="Setting rt_info via ConstOutput"):
+ co.get_rt_info()["iter_key"] = "iter_val"
+
+
def test_multiple_outputs():
input_shape = [4, 4]
input_data = np.arange(-8, 8).reshape(input_shape).astype(np.float32)