(Ab)using the refcount for fast circular-reference checking

I’ve been experimenting with an alternative to the circular-reference tracking used by json. By using a bit in the reference count as a temporary marker, I was able to speed up encoding by roughly 3× in my tests, bringing performance closer to faster alternatives.

Here are the benchmark results on Python 3.13.12, Windows x64:

encode json jsonyx fastsimdjson msgspec orjson fastest time
empty list 10.28x 11.40x 2.26x 2.13x 1.00x 3.38 ns
non-empty list 16.59x 5.45x 1.54x 2.00x 1.00x 9.59 ns
empty dictionary 9.18x 11.69x 2.24x 2.56x 1.00x 3.19 ns
non-empty dictionary 11.89x 4.80x 1.46x 1.90x 1.00x 18.49 ns

The results are relative to orjson. With this change, jsonyx is roughly as fast as when check_circular=False, while still detecting circular references:

>>> import jsonyx as json
>>> lst = [0]
>>> lst[0] = lst
>>> json.dump(lst)
ValueError: Unexpected circular reference (refcount 0x40000007)

The basic idea is to reserve a bit in the reference count to indicate that an object is currently being traversed:

#if SIZEOF_VOID_P > 4
#  define Py_SEEN_FLAG (1U << 30)
#else
#  define Py_SEEN_FLAG (1U << 29)
#endif

if (!_Py_IsImmortal(seq) && (Py_REFCNT(seq) & Py_SEEN_FLAG)) {
    PyErr_Format(
        PyExc_ValueError,
        "Unexpected circular reference (refcount 0x%x)",
        Py_REFCNT(seq));
    return NULL;
}

Py_BEGIN_CRITICAL_SECTION(seq);
Py_SET_REFCNT(seq, Py_REFCNT(seq) | Py_SEEN_FLAG);
Py_END_CRITICAL_SECTION();

/* Process list. */

Py_BEGIN_CRITICAL_SECTION(seq);
Py_SET_REFCNT(seq, Py_REFCNT(seq) & ~Py_SEEN_FLAG);
Py_END_CRITICAL_SECTION();

This is a simplified illustration (error paths must also ensure that the marker is cleared). The main advantage is avoiding the auxiliary data structure and its associated lookup and allocation overhead.

I’d appreciate feedback on a few questions:

  • Is this approach worth considering for the standard library’s json encoder?
  • How should immortal objects be handled?
  • Are the reference-count updates safe on both regular and free-threaded CPython?
  • How should concurrent encodings of the same object be handled, given that one thread could mistake another thread’s marker for a circular reference?
1 Like

In return for a bit of efficiency, you’ve made your encoder single-threaded by design. While you could theoretically pick several different bits to be the marker, in practice there’s still only going to be a finite number of them (and, if you want to be absolutely safe, not very many - on a 32-bit build, you can’t be sure of using more than 2 bits), and it’d make your code more complicated.

Rather than using the refcount, you could appeal for a “temporary bitflags” word (at a cost of extra memory usage on every Python object), but it’s still going to be fundamentally finite, making the benefits come at the cost of thread safety.

1 Like

Cc @vstinner, @ZeroIntensity, @storchaka, @picnixz

I barely needed to check for circular-references. And I don’t think it’s necessary to speed-up that case. If you need to check that, this means your data is likely better to be redesigned in a tree-way instead IMO.

Changing the meaning of the refcount bits is too fragile IMO. And all your questions make me really think that this is not the right approach. Using unrelated refcount information for circular-reference checking just for marking bits is a bad design choice IMO.

3 Likes

One of the reasons the json library checks for circular references is to handle this gracefully. Relying on a recursion error being raised when the C stack overflows is unreliable (e.g. on WASM) and leaves the interpreter in a vulnerable state.

1 Like

Yes, and what is the problem with the current state of the checker? it’s still handling it gracefully. If you are worried about performances, I would suggest that you do it with something other than the stdlib.

Or am I missing something? I am against fiddling with the reference counts for JSON purpose only. The refcount value is part of the interpreter, JSON is an extension module.

Yeah, this seems like it’s fundamentally prone to race conditions (including on the GIL-icious build), so this is a non-starter.

Python 3.14.2 (main, Sep 14 2026 03:03:51) on WebAssembly/Emscripten
>>> import json
>>> lst = [0]
>>> lst[0] = lst
>>> json.dumps(lst, check_circular=False)
Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers.
The cause of the fatal error was:
RangeError: Maximum call stack size exceeded.
Look in the browser console for more details.

In this case, I believe this is a limitation of WASM, not something CPython needs to address. Again, fiddling with refcounting makes a strong -1 for me. With check_circular=True, do we have a fatal error as well? I mean, I don’t what we should expect when check_circular=False and we have a circular structure. The docs say:

If False, the circular reference check for container types is skipped and a circular reference will result in a RecursionError (or worse). Default True.

CPython running on Linux throws RecursionError and carries on. But the “or worse” in the docs is, IMO, fine here. You should only disable the check if you are prepared to take full responsibility for the outcome in the event that it is, in fact, recursive.

My question was more for WASM/WASI, but I think the “or worse” is enough. I should amend one of my previous comments: I thought that check_circular=False was the default but that’s not the case. However, most of the time I believe that people do NOT have circular JSON structures since this also means that they have a circular structure in plain Python.

In particular, if the problem is “JSON is too slow by default because of circular checks”, then the answer to that is not “abuse the refcount” but rather “switch to orjson”.

orjson has a fairly low recursion limit, so that works, but msgspec crashes the interpreter like check_circular=False:

Python 3.14.2 (main, Sep 14 2026 03:03:51) on WebAssembly/Emscripten
>>> import orjson
>>> lst = [0]
>>> lst[0] = lst
>>> orjson.dumps(lst)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: Recursion limit reached
>>> import msgspec
>>> msgspec.json.encode(lst)
Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers.
The cause of the fatal error was:
RangeError: Maximum call stack size exceeded.
Look in the browser console for more details.

I still think that it’s not the business of CPython in those cases. If you have recursive structures, you should be on your own IMO. How frequenlty do we have to encode recursive structures? because in the end the user will essentially need to handle the error somehow.

Once again, I think we are trying to solve a non-issue. I don’t know how to understand the performance numbers either. It says encoding is 10x faster for instance. But AFAICS, the “non-empty dictionary” is not just a random dictionary. It’s a dictionary with immortal keys or values.

What is the effect on realistic data? I still think that anyone worried about JSON encoding performance must not use the stdlib. If being faster requires to fiddle with the bits of recounts, then my take is -1, whatever other argument you have about WASM/WASI which are still tier 2 platforms.

And other issues about data races still make this another -1. I don’t like when we repurpose bits for niche applications.

2 Likes

Well, we don’t (we can’t!), but how often do we have something we need to encode, and only THEN discover that, oopsie, we messed up? Having the guard there is certainly good. Being able to disable the guard to save a bit of performance is nice for when we can be completely sure we’re safe. Beyond that, I agree, this isn’t really Python’s issue.

2 Likes

This is more correct (the previous version could lose increfs):

static int Py_TEST_AND_SET_SEEN(PyObject *op) {
    if (_Py_IsImmortal(op)) {
        return 0;
    }
#ifdef Py_GIL_DISABLED
    return (atomic_fetch_or((_Atomic(uint32_t)*)&op->ob_ref_local, Py_SEEN_FLAG) & Py_SEEN_FLAG) != 0;
#else
    Py_ssize_t refcnt = op->ob_refcnt;
    op->ob_refcnt = refcnt | Py_SEEN_FLAG;
    return (refcnt & Py_SEEN_FLAG) != 0;
#endif
}

static void Py_UNSET_SEEN(PyObject *op) {
    if (_Py_IsImmortal(op)) {
        return;
    }
#ifdef Py_GIL_DISABLED
    atomic_fetch_and((_Atomic(uint32_t)*)&op->ob_ref_local, ~Py_SEEN_FLAG);
#else
    op->ob_refcnt &= ~Py_SEEN_FLAG;
#endif
}

And if you fallback to the more expensive tracking mechanism when the marker is set, there are no issues with multiple threads encoding the same object.

I’m sorry to be blunt but I will say it once: abusing refcounting for this specific task is a no-go from me, whether it’s made safe or not. We don’t want to reserve a refcount for that. People worried about JSON encoding or decoding performances should rather use simdjson or any other third party library.

The issue may no longer be about correctness, but about changing the meaning of deep internals in Python for the purpose of a single extension module. This is not worth the change IMO.

3 Likes

Thanks for the feedback, everyone. The discussion has helped me identify some issues with my initial approach, so I’ve revised it to use atomic operations where necessary and fall back to the usual tracking mechanism when the marker is already set.

I realize this kind of optimization is probably only appropriate for a third-party library, and that using the reference count this way comes with risks that I’m responsible for managing.

I hope some of you at least found this performance hack interesting, even if you wouldn’t want to use it in production.

3 Likes