While working around stan-dev/math#3041, I've encountered the above issue.
My workaround for reduce_sum's inability to take tuple arguments was to first "deconstruct" (flatten) them before passing them to reduce_sum, and then to "reconstruct" (restore the old non-flat structure) them before passing them to the original function.
This however lead to segfaults. The following is AFAICT a minimal reproducer:
R code using cmdstanr 2.36.0
library(cmdstanr)
model = cmdstan_model(
stan_file=paste(getwd(), "stan", "tuples.stan", sep="/"),
)
post = model$sample(
data=list(),
chains=1,
)
Stan code
functions {
void do_something_reconstruct_deconstruct(tuple(array[] int, vector) combined, real x){
do_something_reconstruct(combined.1, combined.2, x);
}
void do_something_reconstruct(array[] int indices, vector mem, real x){
do_something((indices, mem), x);
}
void do_something(tuple(array[] int, vector) combined, real x){
print(combined.1); // This is fine
print(size(combined.2)); // This is fine
print(combined); // This crashes
// print(combined.2); // This crashes
// print(sum(combined.2)); // This crashes
}
}
transformed data {
int n = 2;
array[n] int indices = rep_array(0, n);
vector[n] mem = rep_vector(0., n);
tuple(array[n] int, vector[n]) combined = (indices, mem);
print(combined);
do_something_reconstruct_deconstruct(combined, 1.);
}
parameters {
real x;
}
model {
x ~ std_normal();
print(2);
// This is fine
do_something_reconstruct_deconstruct(combined, 1.);
print(3);
// This is fine
do_something_reconstruct_deconstruct(combined, 1.);
print(4);
// This crashes
do_something_reconstruct_deconstruct(combined, x);
print(5);
// This crashes
do_something_reconstruct_deconstruct(combined, x);
}