Skip to content

gh-162881: Reload list item if storage changes during access - #162994

Open
dpdani wants to merge 3 commits into
python:mainfrom
dpdani:fix/list-get-item-ref-resize
Open

dpdani wants to merge 3 commits into
python:mainfrom
dpdani:fix/list-get-item-ref-resize

Conversation

@dpdani

@dpdani dpdani commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

After incrementing the reference count of item, check that the list array is the one from which the reference was fetched. This avoids the race described in the issue, that leads to list_get_item_ref possibly returning an object that was never in the list.

This needs backports for 3.13, 3.14, and 3.15.

@dpdani

dpdani commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

I have attempted writing a test for this, but it's very unreliable and it requires adding a sleep in list_get_item_ref. Without it, the race just doesn't seem to happen.

There's also the problem that the passing test doesn't prove that the race cannot happen, so a unit test is probably not the right way to go anyway.

Let me know if you have suggestions as to how to test this.

The test (written by the clanker):
    def test_getitem_with_resize(self):
        # gh-162881: an optimistic read from a resized list's old item array
        # must not return an object that was never in the list.

        # Add the following line before _Py_TryXGetRef in list_get_item_ref:
        # nanosleep(&(struct timespec) {  .tv_sec = 0, .tv_nsec = 1000000  }, NULL);

        class Item:
            __slots__ = ("valid", "__weakref__")

            def __init__(self, valid):
                self.valid = valid

        lst = []
        stop = Event()
        bad = []
        retained = []
        writer_errors = []
        padding = (None,) * 64

        def writer():
            try:
                for _ in range(50_000):
                    if stop.is_set():
                        break
                    lst.clear()
                    old = Item(True)
                    old_id = id(old)
                    lst.append(old)
                    del old
                    lst.extend(padding)  # Force a new item array.
                    lst[0] = Item(True)  # Release the object in the old array.

                    candidates = []
                    for _ in range(128):
                        candidate = Item(False)
                        candidates.append(candidate)
                        if id(candidate) == old_id:
                            # Make an optimistic incref from the reader possible.
                            retained.append((candidate, weakref.ref(candidate)))
                            break
                    del candidate, candidates
            except BaseException as exc:
                writer_errors.append(exc)
            finally:
                stop.set()

        with threading_helper.start_threads([Thread(target=writer)],
                                            unlock=stop.set):
            while not stop.is_set():
                try:
                    item = lst[0]
                except IndexError:
                    continue
                if type(item) is not Item or not item.valid:
                    bad.append(item)
                    stop.set()
                    break
                del item  # Do not keep the old item alive during the next read.

        if writer_errors:
            raise writer_errors[0]
        self.assertEqual(bad, [])

@dpdani

dpdani commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

I think the test failure is related to #162963

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant