Having the model write the loop once and run it next to the data is a good way to cut tokens, but the generated code then becomes an execution surface. I'd want it in a sandbox with no ambient credentials, strict CPU/time limits, and an allowlist of the tool bindings it can call, plus logging of the generated script for audit.