Skip to content

Dynamic borrow checking for stackrefs #131527

Closed

Description

@mpage

Feature or enhancement

Proposal:

#130708 introduces stackrefs whose lifetime must be shorter than the lifetime of another stackref. We should verify this property in the debug build of stackrefs: warn anytime a stackref with outstanding borrowed references is closed.

Here is a sketch of a possible implementation:

  • Add a counter, borrows, to each stackref that records the number of borrows.
  • Add a borrowed_from field to each stackref that records the index of the stackref it was borrowed from, if any. This field is preserved by PyStackRef_DUP.
  • PyStackRef_Borrow(from) sets the the borrowed_from field on the returned stackref and increments the borrows field on from. We should follow chains of borrows until we reach the unborrowed reference at the head.
  • PyStackRef_CLOSE on a borrowed stackref decrements the borrows field on the borrowed-from stackref.
  • PyStackRef_CLOSE warns if borrows is non-zero.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Activity

  1. added
    type-featureA feature request or enhancement
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    on Mar 20, 2025
  2. self-assigned this
    on Mar 20, 2025
  3. efimov-mikhail commented on Oct 4, 2025

    @efimov-mikhail
    Member

    I've made a variant of borrow checking which is close to the sketch and it actually works. I've found one little issue with f_overwritten_fast_locals with it. But my implementation depends on #139475. So it seems to merge that PR first.

    CC @markshannon

  4. added a commit that references this issue on Nov 5, 2025
  5. added a commit that references this issue on Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions