Module contents
Lesson 14 of 31Core 100 min

Code execution: the interpreter as a universal tool

Writing and executing code lets a model delegate exact calculations, manipulate data, and check its solutions. Study program-aided reasoning (PAL), code as an agent's action space (CodeAct), isolated execution with time, memory, file, and network limits, and feedback-guided repair compared with resampling under comparable computational budgets.

After this lesson you can

  • Implement program-assisted reasoning and measure which types of error it eliminates and which it does not.
  • Build an isolated execution environment with time, memory, file, and network limits, and verify it with tests of hostile code.
  • Implement an agent that acts by writing code and compare it with one that uses JSON calls.
  • Implement repair with execution feedback and compare it with resampling under the same budget.

Before you start

Delegating the computation does not delegate the interpretation

A textual response can interpret a problem correctly and make a mistake in the final multiplication. An executable program separates interpretation from calculation: the model writes the steps and an interpreter evaluates them. In program-aided reasoning (PAL), that separation moves the calculation to the execution environment. Translating the problem statement into a program remains a model prediction and can be wrong. For example, for 17 packages containing 23 pieces each, 17*23 gives 391; 17+23 executes perfectly and answers a different question.

[ ]A correct account does not show that the setup is correctBrowser
paquetes, piezas_por_paquete = 17, 23
print('multiplicación:', paquetes * piezas_por_paquete)
print('suma:', paquetes + piezas_por_paquete)

PAL and Program of Thoughts study this separation in numerical problems. An interpreter does not eliminate every arithmetic error: the model may generate the wrong operation, use types with inappropriate rounding, enter the wrong number, or misinterpret the output. A comparison should preserve each problem and classify errors from complete traces, rather than comparing only final answers.

The local comparison protocol stores the question, answer, model output, reported usage, and sandbox result for both methods in JSONL. It selects GSM8K test problems with a fixed dataset revision and seed, then creates a variant of each asking for the original numerical answer multiplied by 1 000 000 007. The transformed reference uses exact decimal arithmetic; the variant adds a large operation rather than replacing every quantity in the statement. It requires the pure-Python filter, the sandbox bridge, the isolation files described below, and a local GGUF model. Unrecognized output formats count as failures: distinguishing calculation errors from formulation errors requires inspecting traces afterward and cannot be inferred automatically from the final answer.

Before running a proposal, the filter accepts an explicit subset of constructions and mathematical libraries. A rejected proposal is not executed, it is counted separately and can be an innocent program outside of that subset; that’s why accuracy measures the entire system, not just the model’s capability. Syntax analysis is not a sufficient security barrier and does not replace the operating-system isolation.

The paired analysis requires the complete sample of source problems and variants for both methods, calculates costs, and resamples problems to compare accuracy. The annotation form prepares an explicit error review; labels were assigned by inspecting traces and are available alongside the campaign log.

The problems come from GSM8K, published by OpenAI under the MIT license; this lesson introduces the additional-multiplication variant. The experiment used Qwen2.5-7B-Instruct-GGUF, distributed under Apache 2.0. Its responses come from a local run and are not results reported by the original papers.

Which errors does a calculator eliminate?

Interpreting a result involves four steps: extract quantities from the statement, choose relationships between them, perform the operations, and return the requested quantity with its units. The interpreter helps with the third step if the code expresses the calculation correctly. It cannot tell whether the program confused the number of packages with the number of pieces, omitted a condition, or rounded too early. Exact multiplication of the wrong quantities produces an exact answer to a different problem.

The representation also matters. In Python, integers have arbitrary precision, but floating-point numbers represent approximately many decimals. If a task requires monetary amounts, one can use small integer units or an explicit decimal representation, always provided that the formulation specifies when to round. Divisions by zero, type conversions, or non-numeric outputs should be recorded as execution results, not silently converted to zero. A program that prints several numbers needs an unambiguous extraction rule to avoid accidentally choosing an intermediate value.

In a paired comparison, each method receives the same question and is evaluated with the same reference answer. The large numbers variant is reported separately because it adds an operation and changes the wording, although it shares the original problem. The correct examples do not necessarily reveal that the internal steps are correct: a wrong approach can match the answer by chance. To explain a difference, it is necessary to inspect failures and at least separate interpretation, calculation, execution, format, and evaluation discrepancies. If a person or the assistant itself labels the traces, it is necessary to identify who did it and to preserve the reasons.

The campaign processes the first 500 original questions and then their 500 variants; for each question it queries CoT and PAL consecutively. When comparing families, the order matches the passage of time and the server state may vary between stages. The problem matching does not separate those possible effects, especially in time measurements. This log does not demonstrate that the server state has changed the responses.

A machine interruption halted execution after 1232 saved responses. The campaign resumed from the next row after the existing prefix was verified and the same model and backend were restarted with one slot; that restart also forms part of the observed sequence. Responses before and after the interruption are preserved without assuming that another run would generate identical text.

With the strict final score set before the campaign, CoT correctly answered 182 of the original 500, while PAL got 409; in the variants with large multiplication, they got 42 and 417, respectively. The 95% paired bootstrap for PAL minus CoT is 40.2 to 50.6 percentage points on originals and 71.0 to 79.0 in variants. These are system-wide rates with their prompts, extraction, and filtering: they do not exclusively measure calculation errors nor show that the interpreter causes all the difference.

InteractivePAL and chain of thought

Loading analysis…

Problems
Compare original questions with their variants and inspect errors reviewed by the assistant. Scoring includes formatting, filtering, and execution.

Formatting materially changes the interpretation. After inspecting the traces, an exploratory analysis accepted in addition two concrete forms: a line Final: número surrounded by bold Markdown and a line of LaTeX with \text{FINAL: } followed by the number. With that subsequent rule, CoT accuracy goes from 36.4% to 85.0% on originals and from 8.4% to 27.2% on variants; PAL retains 81.8% and 83.4%. The rule does not recognize all possible presentations and was chosen after inspecting errors: it is a sensitivity test, not the main score nor a definitive measure of reasoning. You can reproduce it with pal_format_sensitivity.py, the log and protocol dependencies.

The assistant reviewed 40 failures per method, alternating between originals and variants in the sample’s fixed order. Of the 40 CoT failures, it attributed 29 to format, eight to calculation, and three to problem formulation; of the PAL failures, it attributed 24 to formulation, nine to format, two to execution, two to filter rejection, two to ambiguity, and one to calculation. These selected cases illustrate errors and do not estimate proportions across the full sample; some traces admit multiple causes. Another assistant reviewed ten original traces without seeing the main labels: its labels included the main category in all ten and additional causes in three. The review and comparison provide a small descriptive check, not independent human annotation.

A discrepancy illustrates the reference’s limits: in gsm8k-403, reducing a 0.9 kW device’s use by five hours daily for 30 days saves 135 kWh, whereas the reference answer is 81, the consumption during the remaining three hours daily. The question also calls an amount of energy ‘kilowatts’. The original score is preserved, and both the original case and its variant are flagged as possible reference discrepancies without retroactively rescoring the batch.

Code as action

The adapter codeact_repair.py offers two variants for the synthetic repair benchmark. One receives actions in batches and re-executes the previous ones within a new isolated process as a proposal arrives; it keeps variables if the actions are reproducible, but may repeat effects. The other uses a persistent session: each action is executed once in the same task interpreter. The session uses session_boot.sh and session_worker.py; on Windows, session_bridge.py and session_cli.py connect through WSL. It is a prototype with the same limited scope as the sandbox, not a hardened boundary. A response that passes visible tests still needs an independent checker; the output messages from the code are untrusted data.

With code as action, the model can combine operations, retain variables and act again after observing the result. This is more flexible than an isolated JSON call, but also expands what the process can attempt. CodeAct studies Python actions in multi-turn interaction; its comparisons depend on the tools, specific models, and concrete tasks.

Persistence means that assigning x = 21 in one action can allow print(x * 2) in the next. It does not mean that the entire host system must share the interpreter. The agent loop receives a bounded observation of an isolated session and maintains its own limits of turns and tokens. Restarting the session clears variables; if it is preserved, it has to be associated with a task and destroyed upon completion.

In this prototype, the code and the session worker share an interpreter: the code could alter Python objects or attempt to interfere with the output protocol. Isolation tests do not demonstrate protocol integrity against adversarial code. The session is useful for studying state and retries with the lab examples; an application that executes hostile code would need a stronger boundary and control channel.

To test the state from Windows, save the five linked session files in the same directory and run the following example there. The with context closes the session and releases its resources on exit; each execute call returns status, output, and whether it was truncated. The example uses harmless code and does not need a model.

from pathlib import Path
import subprocess
from session_bridge import WSLSession

cli = subprocess.check_output(
    ['wsl', '-d', 'Ubuntu', '--', 'wslpath', '-a', str(Path('session_cli.py').resolve())],
    text=True,
).strip()
with WSLSession(cli) as session:
    print(session.execute('x = 21'))
    print(session.execute('print(x * 2)'))

A persistent session and the reproduction of previous actions have different behaviors. If the first action assigns a deterministic variable, reproducing it before the second can restore that value. If the action reads a clock, uses randomness, or increments a counter, repeating it can produce another state. Also, it can re-execute an effect even though the agent believes it only continues. The log should indicate which variant was used and preserve all actions. The CodeAct repair prototype offers the persistent session; a test with simulated actions confirmed that a counter maintains its value without repeating previous actions. The MBPP comparison of this lesson evaluates each candidate in a new isolated process.

A minimal, reproducible comparison of action spaces uses twenty tasks that calculate (a+b)c(a+b)c. The executable control uses a fixed rule planner, not a model: one variant sends a Python action that sums and multiplies; the other sends a JSON call to sumar and another to multiplicar, with schema and integers validated. Each method uses a separate WSL session for each task. In one run, both solved 20/20; the Python protocol used 20 actions and the JSON, 40. This shows the composition allowed by those two interface designs, not a model capability advantage nor a fair latency comparison. If the JSON tool offered a composite operation, it could also solve each task in one call: the difference depends on the available catalog.

The flexibility of expressing a loop does not guarantee that the agent understands what it did. An observation may contain an exception, partial output, or a value printed by the code itself. The host separately preserves the process state, received bytes, and the checker result. The model can use the observation to propose the next action, but the test-running program should not trust a phrase like ‘all tests pass’ if the code itself can print it.

Layered isolation

An isolated execution environment (sandbox) restricts the resources and permissions available to code. A time limit combats non-terminating loops; a memory limit bounds allocations; an ephemeral root avoids presenting the process with the host’s files; networking and process creation are restricted by system mechanisms. Output must be drained during execution: waiting until completion to read a stream that fills can block both processes. The mechanisms depend on the operating system and must fail closed if they cannot be activated.

InteractiveTests and layers of isolation
Infinite loop

The process wrote 'started' and stopped upon reaching the 45-second timeout.

The observations correspond to the battery of the prototype executed in Ubuntu WSL; passing it does not establish security against arbitrary code.

Examined layerHost deadline
ResultObserved test
Select a test and distinguish what was observed with the active layers of the hypothesis when disabling one. The result of a specific batch does not demonstrate universal isolation.

In the laboratory prototype, user, mount, network, and PID namespaces were created in Ubuntu WSL; a temporary root was mounted, capabilities were removed, a system call filter was applied, and memory and file size were limited. The test process appears as UID 0 inside its namespace, but it corresponds to a regular account outside; it is not the same as granting administrative privileges to the host process. That distinction is described in user_namespaces(7). The call filter is just one piece of defense: the kernel documentation warns that seccomp by itself is not a complete sandbox.

The test suite exercises a loop, a large allocation, a host path, a socket, and attempted process creation. Passing it establishes results for those cases and that configuration, not security for arbitrary code or suitability for multitenant isolation. The output and protocol of the process are also untrusted data: a message should not be accepted as evidence of correctness just because it was written by the examined code.

The reproducible prototype consists of sandbox.py, sandbox_boot.sh, worker.py and test_sandbox.py. Download the four in a directory of Ubuntu WSL and execute python3 test_sandbox.py. Requires Python 3.12 in /usr/bin, unshare, setpriv, chroot and libseccomp.so.2, in addition to a kernel that allows user and mount namespaces. If preparation fails, it does not execute code outside of isolation. Memory and output limits are part of the example and must adapt to the environment and task.

The host writes the request and reads the output without blocking on a full pipe, measures the time from before startup and kills its own child process group when the deadline expires. The loop test requires first receiving an innocuous start marker, so that a timeout during preparation is not mistaken for a loop that actually started. Upon completion, the host deletes the temporary directory. The test process shares the system kernel and the code can produce its own output; this implementation is a bounded laboratory, not a hardened boundary nor a hostile production code evaluator.

Preparation, execution, and cleanup

The host cycle starts by preparing a new directory and configuration for each task. Before delivering code, it must know if the intended mechanisms were activated; if a preparation stage fails, the result is an infrastructure error, not a less-restricted execution. At the end, it collects the output state and cleans up the resources it created. The test of closing stdout and stderr followed by a loop is useful because it shows that the end of output does not imply the end of the process: the deadline must remain active even after receiving EOF.

Unlimited outputs can exhaust memory even if the computation is simple. A concurrent reader prevents the child from being blocked waiting for the pipe to empty and retains at most the agreed limit. If the limit is exceeded, it must be recorded that the output was truncated; an incomplete trace can hide both a subsequent error and the answer. The memory limit, in turn, does not replace the time limit, and neither controls what files or sockets the process can open. Each layer answers a different question.

An isolation test must identify the desired effect and the observation. For the host path, the case verifies that a specific path is not available under the temporary root; for the network, it verifies a specific socket operation; for processes, a specific attempt at creation. An observed rejection does not prove that all possible paths, protocols, or calls are blocked. Repeat the tests in the system where the laboratory will be used and keep the kernel version, configuration, output codes, and errors. If a production boundary is needed, its evaluation must cover a broader threat model than these teaching tests.

The state of the protocol helps to not mix causes. An exception returned by the program within the worker is an observation of the executed code. In contrast, a failure to start isolation or a response that does not comply with the worker protocol does not allow concluding what the program would have done. In the PAL and MBPP launchers, an ambiguous state of the sandbox interrupts the campaign before saving that condition as success or failure. The previous rows and their configuration are preserved to resume after investigating the problem.

A timeout can be ambiguous if the deadline includes both preparation and execution and there is no reliable signal that the program has started. The sandbox battery uses a start marker to confirm the loop case, but an arbitrary program is not obligated to emit it. The absence of that marker in a campaign does not identify the cause by itself. For this reason, the protocol is conservative: an indeterminate result is not incorporated into the denominator as if it were a wrong answer. A campaign that is interrupted should not be summarized as if it included all the expected problems.

The undecidability of the halting problem explains why there does not exist a general checker that decides in advance whether any arbitrary program will terminate. A timeout also kills legitimate programs that need more time: it is an operational policy, not a proof that the program will never terminate.

Repair or try again

The execution feedback repair returns a failure signal to the model, for example a test that fails or a short trace. It can then propose a different version. Self-Debugging studies execution and explanation of programs as debugging signals; a single improvement is not enough to attribute it to repair. Compare it with new independent samples using the same task distribution and token budget, and report both the cost and the number of calls. Visible tests help the agent; held-out tests measure generalization and must remain inaccessible to it.

Assuming independence, if each fresh sample succeeds with probability pp, the probability of success within nn samples is 1−(1−p)n1-(1-p)^n. If the first succeeds with probability pp and each one of the n−1n-1 repairs after a failure has conditional probability qq, success is 1−(1−p)(1−q)n−11-(1-p)(1-q)^{n-1}. Formulas are not an empirical law of the model: errors and repairs can be correlated and their probabilities can change with history.

The fair comparison requires declaring which budget is being equated. Four calls with a maximum of 4096 tokens can consume different amounts, and a strategy that uses one call to explain the failure has fewer calls to produce candidates. Registering input and output tokens, time, and the number of candidates allows tracing curves of success against observed cost. A common ceiling prevents one variant from exceeding the maximum, but it does not prove that it has spent exactly the same. If points of different cost are compared, that difference must be shown alongside the success. Token curves reproduce the logged calls under a hypothetical ceiling: they discard the first incomplete call, include its simulated cost, and select among complete candidates. They were not re-sent to the model with that ceiling; the replay assumes that the prefixes would have been the same with a lower limit, something that is not guaranteed.

The feedback also changes the available information. A binary indicator only says whether a set of tests passed; a trace can reveal the line that failed and a concrete example. Both can help repair, but also allow adapting the candidate to the visible tests. Held-out tests are applied after generating the proposals and are not returned as feedback during the search. It is advisable to preserve the intermediate proposals and evaluate each prefix to distinguish a repair that improves the result from another that only increases the number of attempts.

Interpreting a sequence of attempts

Suppose that the first proposal fails due to an out-of-range index. A second changes the condition and passes the visible example. It may have fixed the cause, but it could also have added a specific exception for that example. A held-out set with lists of different lengths and empty cases allows examining that risk; its content must remain out of the prompt and the traces returned to the agent. If the held-out cases fail, the report preserves the improvement in the visible test and the failure of generalization as distinct observations.

To compare repair and resampling, match each method by problem and present the result after one, two and more candidates, always with the information available for each condition. The method with feedback can spend additional tokens in reading a trace; the resampling method can generate more solutions without seeing errors. A textual reflection adds another call and can change the next prompt, so its cost also counts. The comparison should include all those calls even if one does not produce code directly.

The probabilities of the example cell suppose independence and constant values of pp and qq. In a real interaction, each repair sees the history and can have a different probability. Generally, the probability of failing all attempts is the product of the conditional failure probabilities given previous failures, provided those probabilities are defined. That chain rule requires no independence assumption; replacing all factors with a single constant does require additional assumptions. Estimating those factors requires sufficient trajectories and a consistent definition of failure.

The error analysis must also accommodate uncertainty. A program that runs correctly but gives a wrong answer may have a problem with formulation, units, conversion, or evaluation. It is useful to note the line or evidence that supports the classification and review ambiguous cases, instead of automatically assigning all discrepancies to ‘arithmetic’. If the review is done by the assistant, those annotations are identified as such and are not presented as independent human evaluation.

Classification can admit more than one cause or a ‘non-conclusive’ category. It also retains the version of the rubric and the trace fragment that led to each decision, so that another review can discuss it.

For a programming repository, record which tests are shown to the model and which are held out for evaluation. In this MBPP protocol, the first one is shown and the rest, along with additional cases, are kept until candidates are fully generated. They are public tests from the set, not secret information against any pre-trained model, and they are executed in the same isolated process as the code: that limits what can be asserted about contamination and resistance to manipulation. The result is an evaluation of this procedure, not a guarantee of correctness for all inputs.

The fixed manifest selects 50 tasks before consulting the model, through the seed and filter applied to the reference solutions and their tests. The selection excludes tasks outside the accepted subset; the reference solutions of the 50 selected tasks passed both the visible tests and the held-out ones in WSL. This verifies the bank and the environment, not the model score. The four methods receive the same prompt, seed, and output ceiling in their first attempt; subsequent reflection calls share the remaining output budget. To obtain curves by prefix, the protocol may continue generating up to three candidates even if one already passed the visible test; selection still keeps the first candidate that passed. Filter rejections are kept as such in the logs and count in the system denominator.

In the local run with quantized Qwen2.5-7B-Instruct and a limit of three calls, resampling and binary feedback each solved 27 of 50 tasks, trace feedback solved 28, and trace feedback with reflection solved 29. Their complete prefixes cost, respectively, a mean of 631, 797, 829, and 883 input and output tokens per task. Compared to resampling, the 95% paired bootstrap interval for the difference was -4 to 10 percentage points with trace and -4 to 12 with reflection. These are sample and procedure results, compatible with differences in either direction; the observed costs are not equal.

InteractiveRepair and budget

Loading analysis…

Budget axis
Compare success in held-out tests, paired difference, and simulated spending when applying a token ceiling to logged calls.

Although the first prompt, the seed, and the output ceiling were the same, only 15 of the 50 tasks produced exactly the same initial text in the four conditions; in 47, the visible and held-out initial results matched. Token counts were saved, not their sequences. The origin of these differences was not isolated: that is why the paired contrast includes the four real trajectories per task and does not allow attributing a difference solely to feedback or a specific server mechanism. The complete analysis of the 200 conditions can be consulted in the data of the figure.

The reproducible replay uses the full log of the 200 conditions, analyze_mbpp.py and the evaluation library. Save the four files in the same directory and execute python replay_mbpp_budget.py mbpp-7b.jsonl replay.json. An independent check contrasted the 1600 combinations of task, method, and ceiling. At 512 tokens available, resampling, trace feedback, and reflection solve 27, 28, and 26 tasks, with simulated costs of 468, 433, and 403 tokens; the equality is of the available budget, not the cost. A call that leaves no margin for at least one output token is not sent; if it remains incomplete, its response is discarded and the simulated cost is counted. If there is still no complete candidate, an abstention is recorded.

To apply the limit online in a new execution, the executable ledger receives a generator, a sandbox, and a token counter that must reproduce exactly the server template. Before each call, it reserves the input cost and limits output to the available balance; it stops if the server reports a different input cost. It uses only complete candidates, selects using the visible test, and queries held-out tests at the end. Download it along with mbpp_protocol.py and pure_python.py; the function assumes a configured sandbox and does not provide isolation on its own. The ledger was tested with simulated generator and sandbox; it has not yet been measured online with the 7B.

The adapter generate(prompt, max_tokens, attempt) returns text and a dictionary with prompt_tokens, completion_tokens and finish_reason; count_prompt(prompt) counts tokens using the same template as that generator. With an MBPP task and the three functions already configured, the entry point is:

from mbpp_online_budget import run_online

result = run_online(task, 'repair', generate, sandbox, count_prompt,
                    total_budget=1024, rounds=2)
print(result['success'], result['spent_input'], result['spent_output'])

The tasks and tests come from MBPP, Google Research, distributed under CC BY 4.0 and presented by Austin and collaborators; the selection and the division between visible and held-out tests are decisions of this lesson’s protocol.

If the first candidate that passes the visible test is selected, the held-out verifier must evaluate that selected candidate and not retrospectively choose the best among all who failed publicly. Otherwise, evaluation information is used for selection and the rate stops representing the declared policy. The prefix curves from the MBPP analyzer apply the same rule to candidates available up to each cost and use paired_bootstrap from the lesson 4 evaluation library. If you run the analyzer downloaded separately, save both files in the same directory. Paired resampling resamples problems while keeping the methods’ results together; it does not convert a small or correlated set into a universal sample.

The protocol also preserves the responses that do not contain interpretable code. Excluding them before calculating the rate would artificially increase the success rate among the remaining ones. Instead, infrastructure incidents do not offer a valid response about the method and should be investigated or repeated before closing the pair. The distinction depends on a clear record of which stage produced each error.

When a case repeats due to an incident, keep the original seed and protocol and record the repetition. If the previous result was conclusive, replacing it just because it was unfavorable would alter the evaluation. A resumption rule written before the campaign helps distinguish both cases.

[ ]Three calls under explicit hypothesesBrowser
p, q = 0.3, 0.25
print('remuestreo:', 1 - (1 - p)**3)
print('una muestra y dos reparaciones:', 1 - (1 - p)*(1 - q)**2)
Numeric
With p=0.3 for a new sample and q=0.25 for repair after a failure, according to the previous hypotheses, calculate the probability of success for a sample and two repairs.
Quiz
Why do restricting builtins and running generated code inside the agent's process fail to provide isolation by themselves?
Quiz
Why is a deadline needed even if the model normally produces correct code?

Execution exercises

Code
Implement run_bounded(code, timeout, limit): runs a child Python with code, reads its output without waiting for it to finish and returns (state, bytes). The states are ok, timeout, and output_limit. If the timeout expires or the output exceeds limit, it terminates the child and keeps at most limit bytes. This exercise uses only benign programs: limiting a process does not turn it into a sandbox.
def run_bounded(code, timeout, limit):
  pass
Shift+Enter to run
Code
Implement dispatch(actions, session, limit). session is an already opened isolated interpreter and its method execute(code) returns {'status': 'ok' or 'error', 'output': text}. Send each action exactly once and in order to that same session; return a list of objects with status and output truncated to limit characters. If the protocol returns an invalid result, raise RuntimeError. The adapter assumes isolation and never executes code in the agent's process.
def dispatch(actions, session, limit):
  pass
Shift+Enter to run

Summary

Key idea
The interpreter calculates what the program expresses, not what the problem intended; executing generated code requires verifiable isolation and comparison of repair with alternatives under comparable budgets.