Skip to content

gh-128844: Make _Py_TryIncref public as an unstable API. #128926

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Doc/c-api/object.rst
Original file line number Diff line number Diff line change
Expand Up @@ -613,3 +613,33 @@ Object Protocol
.. versionadded:: 3.14
.. c:function:: int PyUnstable_TryIncRef(PyObject *obj)
Increments the reference count of *obj* if it is not zero. Returns ``1``
if the object's reference count was successfully incremented. Otherwise,
this function returns ``0``.
:c:func:`PyUnstable_EnableTryIncRef` must have been called
earlier on *obj* or this function may spuriously return ``0`` in the
:term:`free threading` build.
This function is logically equivalent to the following C code, except that
it behaves atomically in the :term:`free threading` build::
if (Py_REFCNT(op) > 0) {
Py_INCREF(op);
return 1;
}
return 0;
This is intended as a building block for safely dealing with unowned
references without the overhead of creating a :c:type:`!PyWeakReference`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In C API docs the term borrowed reference is more common than unowned reference, can you use that?

There's a glossary entry for it so it can be linked to that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll update the term, but I don't love the use of "borrowed reference" here. This seems different to me than the typical use of "borrowed reference" -- there's not a particular reference that's borrowed here. It's more like a building block for weak reference like objects without using PyWeakReference.

* Note that this is a stealth reference: wr_object's refcount is

.. versionadded:: 3.14
.. c:function:: void PyUnstable_EnableTryIncRef(PyObject *obj)
Enables subsequent uses of :c:func:`PyUnstable_TryIncRef` on *obj*. The
caller must hold a :term:`strong reference` to *obj* when calling this.
.. versionadded:: 3.14
6 changes: 6 additions & 0 deletions Include/cpython/object.h
Original file line number Diff line number Diff line change
Expand Up @@ -541,3 +541,9 @@ PyAPI_FUNC(PyRefTracer) PyRefTracer_GetTracer(void**);
* 0 if the runtime ignored it. This function cannot fail.
*/
PyAPI_FUNC(int) PyUnstable_Object_EnableDeferredRefcount(PyObject *);

// Increments the reference count of the object, if it's not zero.
// PyUnstable_EnableTryIncRef() should be called on the object
// before calling this function in order to avoid spurious failures.
PyAPI_FUNC(int) PyUnstable_TryIncRef(PyObject *);
PyAPI_FUNC(void) PyUnstable_EnableTryIncRef(PyObject *);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add :c:func:`PyUnstable_TryIncRef` and :c:func:`PyUnstable_EnableTryIncRef`
unstable APIs. These are helpers for dealing with unowned references in
a thread-safe way, particularly in the free threading build.
53 changes: 53 additions & 0 deletions Modules/_testcapi/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,66 @@ pyobject_enable_deferred_refcount(PyObject *self, PyObject *obj)
return PyLong_FromLong(result);
}

static int MyObject_dealloc_called = 0;

static void
MyObject_dealloc(PyObject *op)
{
// PyUnstable_TryIncRef should return 0 if object is being deallocated
assert(Py_REFCNT(op) == 0);
assert(!PyUnstable_TryIncRef(op));
assert(Py_REFCNT(op) == 0);

MyObject_dealloc_called++;
Py_TYPE(op)->tp_free(op);
}

static PyTypeObject MyType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "MyType",
.tp_basicsize = sizeof(PyObject),
.tp_dealloc = MyObject_dealloc,
};

static PyObject *
test_py_try_inc_ref(PyObject *self, PyObject *unused)
{
if (PyType_Ready(&MyType) < 0) {
return NULL;
}

MyObject_dealloc_called = 0;

PyObject *op = PyObject_New(PyObject, &MyType);
if (op == NULL) {
return NULL;
}

PyUnstable_EnableTryIncRef(op);
#ifdef Py_GIL_DISABLED
// PyUnstable_EnableTryIncRef sets the shared flags to *at least*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment seems incomplete, can you elaborate it a bit more?

assert((op->ob_ref_shared & _Py_REF_SHARED_FLAG_MASK) >= _Py_REF_MAYBE_WEAKREF);
#endif

if (!PyUnstable_TryIncRef(op)) {
PyErr_SetString(PyExc_AssertionError, "PyUnstable_TryIncRef failed");
Py_DECREF(op);
return NULL;
}
Py_DECREF(op); // undo try-incref
Py_DECREF(op); // dealloc
assert(MyObject_dealloc_called == 1);
Py_RETURN_NONE;
}

static PyMethodDef test_methods[] = {
{"call_pyobject_print", call_pyobject_print, METH_VARARGS},
{"pyobject_print_null", pyobject_print_null, METH_VARARGS},
{"pyobject_print_noref_object", pyobject_print_noref_object, METH_VARARGS},
{"pyobject_print_os_error", pyobject_print_os_error, METH_VARARGS},
{"pyobject_clear_weakrefs_no_callbacks", pyobject_clear_weakrefs_no_callbacks, METH_O},
{"pyobject_enable_deferred_refcount", pyobject_enable_deferred_refcount, METH_O},
{"test_py_try_inc_ref", test_py_try_inc_ref, METH_NOARGS},
{NULL},
};

Expand Down
14 changes: 14 additions & 0 deletions Objects/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -2590,6 +2590,20 @@ PyUnstable_Object_EnableDeferredRefcount(PyObject *op)
#endif
}

int
PyUnstable_TryIncRef(PyObject *op)
{
return _Py_TryIncref(op);
}

void
PyUnstable_EnableTryIncRef(PyObject *op)
{
#ifdef Py_GIL_DISABLED
_PyObject_SetMaybeWeakref(op);
#endif
}

void
_Py_ResurrectReference(PyObject *op)
{
Expand Down
2 changes: 2 additions & 0 deletions Tools/c-analyzer/cpython/ignored.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,8 @@ Modules/_testcapi/exceptions.c - PyRecursingInfinitelyError_Type -
Modules/_testcapi/heaptype.c - _testcapimodule -
Modules/_testcapi/mem.c - FmData -
Modules/_testcapi/mem.c - FmHook -
Modules/_testcapi/object.c - MyObject_dealloc_called -
Modules/_testcapi/object.c - MyType -
Modules/_testcapi/structmember.c - test_structmembersType_OldAPI -
Modules/_testcapi/watchers.c - g_dict_watch_events -
Modules/_testcapi/watchers.c - g_dict_watchers_installed -
Expand Down
Loading