[R] ALTREP crash in base R due to use-after-free
Describe the bug, including details regarding any error messages, version, and platform.
arrow::array_string_vector Elt() method returns a newly created CHARSXP without keeping it reachable from the source vector, leading to a crash/segfault. Here is a short minimal reproducer: https://gist.github.com/traversc/a5204821451198d457edc38cceda9d90
This is the same class of bug as in vroom https://github.com/tidyverse/vroom/pull/638. vroom's fix is to cache accessed strings on the external pointer's protected slot and reuse that cache on materialize.
I understand when ALTREP became available, it was understood that CHARSXPs did not need to be rooted. But that was never correct and was a latent bug for many years. See here for more details: https://bugs.r-project.org/show_bug.cgi?id=19135
Component(s)
R
Thanks for reporting this @traversc; confirmed this can replicate from the reproducer on Arrow 25.0.0 and R 4.6.1.
take
@emecii Let's discuss solutions here before we get into a PR, given this will touch the internals of the R package.
Thanks — I agree that the lifetime strategy should be settled first.
My proposed minimal direction mirrors the vroom approach: attach a STRSXP element cache to the existing ALTREP data1 external pointer with R_SetExternalPtrProtected. Elt() would return an already-cached CHARSXP, or convert once and store it in that cache before returning it. Materialize() would reuse any cached elements while filling the final representation, then clear both the cache and the existing chunked-array reference.
That keeps each CHARSXP reachable through the ALTREP object, avoids changing the public R API, and preserves the materialization path. I have a focused gctorture() regression based on the report's non-interned Latin-1 payload ready to validate this direction.
The C++ source compiles locally, but my macOS R package build currently cannot load its arrow.so because its generated link flags omit RE2, so I have not opened a PR or treated the local change as validated. Does the protected STRSXP cache approach match the intended ownership model before I finish the runnable R test path?
I'm probably not going to engage in more discussion here or review a PR for this issue that isn't from someone I know to be an experienced R dev or experienced Arrow contributor without clear signs of human life behind them as we get a lot of AI-generated discussions and PRs these days and they take longer to review than just doing it ourselves.
Issue resolved by pull request 51288 https://github.com/apache/arrow/pull/51288