#2458·tokenizers

[1.0.0rc2] Encoding.ids_array panics while another thread decodes the ids

Author: nimbrelCreated Sep 26, 2026Updated Sep 28, 2026

Reading enc.ids_array while another thread runs tok.decode() on that same array raises PanicException: called `Result::unwrap()` on an `Err` value: AlreadyBorrowed. It happens on the normal GIL build. A thread pool where one worker decodes an encoding while another reads its arrays hits it. PanicException derives from BaseException, so except Exception misses it and the thread dies.

python
import threading
from tokenizers import Tokenizer

tok = Tokenizer.from_pretrained("openai-community/gpt2")
enc = tok.encode("the quick brown fox jumps over the lazy dog. " * 90)
ids = enc.ids_array
errors = []

def decode():
    for _ in range(300):
        tok.decode(ids)

def view():
    for _ in range(2000):
        try:
            enc.ids_array
        except BaseException as e:  # PanicException is not an Exception
            errors.append(str(e))

threads = [threading.Thread(target=decode), threading.Thread(target=view)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"{len(errors)}/2000 ids_array calls panicked", set(errors))

On CPython 3.14.2, 1045 to 2000 of 2000 calls panic (3/3 runs), and 571 to 2000 on 3.12.12. On 3.14t it is 5 to 47 of 2000. decode_tokens, type_ids_array and attention_mask_array are affected too, and on 3.14t two threads that only read ids_array also panic, sometimes with releasing an exclusive reference should immediately permit a shared reference: AlreadyBorrowed.

Versions: tokenizers 1.0.0rc2 (PyPI), numpy 2.5.3, CPython 3.14.2, 3.12.12 and 3.14.2t, Linux x86_64.

view() takes an exclusive readwrite() borrow of the shared base on every getter call, only to mark the new array read-only. decode() holds a shared rust-numpy borrow of the same array across py.detach, so the exclusive borrow fails and panics. rust-numpy documents that its borrows are not synchronized between threads.

https://github.com/huggingface/tokenizers/blob/7616272a1b0b580fb43e3a06701fd11db9a2706a/bindings/python/src/encoding.rs#L116-L124 https://github.com/huggingface/tokenizers/blob/7616272a1b0b580fb43e3a06701fd11db9a2706a/bindings/python/src/tokenizer.rs#L342

Clearing the flag on the new array avoids the borrow. With this the script reports 0/2000 on 3.14.2 and 3.14t (3/3 each) and the arrays stay read-only:

diff
-use numpy::{PyArray1, PyArrayMethods};
+use numpy::{PyArray1, PyUntypedArrayMethods};
-    array.readwrite().make_nonwriteable();
+    // SAFETY: `array` was just created and is not shared yet.
+    unsafe { (*array.as_array_ptr()).flags &= !numpy::npyffi::flags::NPY_ARRAY_WRITEABLE };

Found with ftcheck.