Notes on evaluating coding agents
Some observations from evaluating coding agents, including a SymPy optimisation bug and a problem with SQL generation.
Over the past few months, I have been working with coding agents on several open-source repositories. In some cases, I worked with two agents on the same problem and compared their implementations before deciding which one to continue with. I wanted to write about a few of these experiences, starting with a problem in SymPy that took several iterations to understand and resolve.
SymPy
SymPy is a Python library for symbolic mathematics. Among other things, it provides a function called lambdify, which converts a symbolic mathematical expression into a callable function. We can use it, for example, to construct a Python function from an expression involving trigonometric functions.
1
2
3
4
5
6
from sympy import symbols, sin, lambdify
x = symbols("x", real=True)
expr = sin(x) + sin(x)**2
f = lambdify(x, expr, modules="math")
Calling f(2) evaluates the expression using Python’s math module. Since the expression contains two occurrences of sin(x), we can avoid calculating it twice by enabling common subexpression elimination (CSE). This is an optional optimisation in lambdify which extracts common expressions into temporary variables.
1
f = lambdify(x, expr, modules="math", cse=True)
The resulting function would look something like this:
1
2
3
def _lambdifygenerated(x):
x0 = sin(x)
return x0**2 + x0
The problem I was looking at concerned expressions that contain conditions. SymPy allows us to represent these using Piecewise, where each expression is associated with a condition under which it should be evaluated.
1
2
3
4
5
6
from sympy import Piecewise, Eq
expr = Piecewise(
(1, Eq(x, 0)),
(sin(x) / x, True)
)
Here we have defined a function that returns 1 at zero and evaluates sin(x) / x everywhere else. Suppose we want to generate a function that returns both the value of this expression and its derivative, using the appropriate values of 1 and 0 at zero. Since both expressions contain sin(x) and 1/x, enabling CSE can move these calculations into temporary variables at the beginning of the generated function.
The generated code was essentially equivalent to the following:
1
2
3
4
5
6
7
8
def f(x):
a = sin(x)
b = 1 / x
return [
1 if x == 0 else a * b,
0 if x == 0 else cos(x) * b - a / x**2
]
Calling this function with zero results in a ZeroDivisionError because the division is performed before the condition is evaluated. The call to sin(x) is also unnecessary at zero, since neither of the results depends on it in that case.
We could avoid this problem by preventing CSE from extracting expressions that occur within conditional branches, but doing so would defeat the purpose of enabling the optimisation. For non-zero values of x, we still want both expressions to use the same calculated value of sin(x).
To check that the optimisation continued to work, the regression test used a wrapper around math.sin to count the number of times it was called. At zero, the generated function should return [1, 0] without calling sin. At math.pi, it should calculate both results while calling sin only once.
Comparing the implementations
One of the agents solved the problem by delaying the evaluation of the temporary variables until their values were needed. The following is the function it generated, which I have reformatted slightly for readability.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def _lambdifygenerated(x):
x0 = (x == 0)
x1 = None
x2 = None
return [
(
1 if x0 else
(x1 if x1 is not None else (x1 := sin(x))) *
(x2 if x2 is not None else (x2 := 1/x))
),
(
0 if x0 else
-(x1 if x1 is not None else (x1 := sin(x))) / x**2 +
(x2 if x2 is not None else (x2 := 1/x)) * cos(x)
)
]
The variables x1 and x2 are initially set to None. When an expression needs the value of either variable, it checks whether that value has already been calculated. If it hasn’t, the assignment expression calculates and stores it. At zero, neither variable is used, so neither calculation takes place.
The other agent generated code using ordinary if and else statements, which made the resulting function much easier to read. However, there was a considerable difference in the amount of code needed to produce these functions. The first implementation changed 106 lines in lambdify.py, while the second changed 474.
Normally, I would prefer the more readable function, but in this case the function is generated by SymPy and is not something a developer would ordinarily have to maintain. The code that generates it, on the other hand, will have to be maintained. Unless the larger implementation provided some additional benefit beyond the readability of the generated function, I saw little reason to prefer it. Both implementations worked for the cases we had tested, and I continued with the smaller one.
Other conditional expressions
I was also interested in what would happen if a common subexpression appeared in a condition as well as in one of the expressions associated with it.
1
2
3
4
5
6
7
from sympy import log
expr = Piecewise(
(7, x <= 0),
(1, log(x) < 1),
(log(x), True)
)
When x is negative, this function should return 7 without evaluating log(x). When x is greater than e, it has to calculate log(x) to determine whether the second condition is satisfied. Since it isn’t, the function proceeds to the last expression, where it needs the value of log(x) again.
I wanted to make sure that the value calculated while evaluating the condition was reused in the last expression. I also asked for a test involving nested Piecewise expressions, where the evaluation of log(y) depended on both x and y being positive. The existing implementation handled both cases without any further changes to lambdify.py.
The same was not true of boolean expressions. Consider the following pair of expressions, which contain a common comparison involving log(x).
1
2
3
4
5
6
from sympy import And, Or
checks = (
And(x > 0, log(x) > 0),
Or(x <= 0, log(x) > 0)
)
Without CSE, the scalar Python code generated for these expressions evaluates the comparison involving x before evaluating the logarithm. Since Python’s and and or operators use short-circuit evaluation, neither expression needs to evaluate log(x) when x is negative.
Enabling CSE causes the comparison log(x) > 0 to be extracted into a temporary variable. Although the earlier fix provided a way to delay the evaluation of such variables, SymPy’s printer also sorts the operands of And and Or using a function called default_sort_key. Replacing one of the operands with a symbol changes where it appears in the sorted order.
A condition that would otherwise have been generated as:
1
(x > 0) and (log(x) > 0)
could now be generated as:
1
x0 and (x > 0)
Even if the value of x0 is calculated only when it is needed, it is now needed before the comparison involving x. The previous fix could not prevent the logarithm from being evaluated for negative values.
The implementation was extended so that the printer could sort the operands according to the original expressions rather than the temporary symbols introduced by CSE. After this change, the generated function looked like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
def _lambdifygenerated(x):
x0 = None
return (
(
(x > 0) and
(x0 if x0 is not None else (x0 := (log(x) > 0)))
),
(
(x <= 0) or
(x0 if x0 is not None else (x0 := (log(x) > 0)))
),
)
The results and the number of calls to log were as follows:
| Input | Result | Calls without CSE | Calls with CSE after the fix |
|---|---|---|---|
-1 | (False, True) | 0 | 0 |
0.5 | (False, False) | 2 | 1 |
2 | (True, True) | 2 | 1 |
This does not mean that SymPy now evaluates boolean operands in the order in which we write them. The printer could reorder operands before any of these changes were made, and there are expressions for which an invalid logarithm would be evaluated even with CSE disabled. The intention was to preserve the evaluation order of the code that SymPy would have generated without the optimisation, rather than change the existing behaviour of the printer.
Testing the implementation
While investigating the original bug, one of the agents wrote a Python script in /tmp and executed it from the SymPy repository. It assumed that the script would import SymPy from the current working directory. However, Python puts the directory containing the script at the beginning of its module search path, and in this environment the script ended up importing the copy of SymPy installed through pip in /usr/local/lib/python3.12/dist-packages.
The agent noticed this later and repeated the experiment against the unmodified checkout. The same exception occurred, so its original diagnosis was correct. In a similar situation where the installed version and the local checkout behaved differently, it could have spent a considerable amount of time investigating a problem that did not exist in the code it was supposed to be modifying.
There was also some confusion regarding which backends had been tested. One of the agents reported testing the math, mpmath, cmath and default backends, but the script it had executed passed ["math", "mpmath", "sympy"] as its last value for the modules argument. Omitting the argument entirely allows SymPy to select a backend depending on which libraries are installed. Since the way conditional expressions are evaluated differs between scalar and array-oriented backends, I asked the agent to report the actual arguments it had used rather than describe them collectively.
SQL import and generation
I was also working with an application for creating entity-relationship diagrams from database schemas. I wanted to introduce a project explorer similar to the one in SQL Server Management Studio, where the schemas and tables belonging to a project could be browsed individually. The application already supported importing SQL files, but the import functionality needed to be extended to extract schema names from the table definitions.
Part of the SQL used during testing looked like this:
1
2
3
4
5
6
7
CREATE TABLE [common].[LocationType]
(
[LocationTypeID] INT NOT NULL IDENTITY(1,1),
[LocationTypeDescription] VARCHAR(25) NOT NULL,
[IsPhoneLocationType] BIT NOT NULL DEFAULT (0),
[IsAddressLocationType] BIT NOT NULL DEFAULT (0)
);
The complete file contained additional tables belonging to the dbo and org schemas. One agent initially imported all the tables into dbo, while the other preserved their respective schema names. This was easy to identify from the project explorer, and subsequent changes addressed the problem.
Something that was missed during testing concerned the SQL generated by the application itself. The application allowed us to view the SQL for an individual table as well as the SQL for the entire project. When viewing the definition of common.LocationType, the two BIT columns correctly appeared as follows:
1
2
[IsPhoneLocationType] BIT NOT NULL DEFAULT (0),
[IsAddressLocationType] BIT NOT NULL DEFAULT (0)
When viewing the SQL for the entire project, however, the default constraints were missing.
1
2
[IsPhoneLocationType] BIT NOT NULL,
[IsAddressLocationType] BIT NOT NULL
If the database were created using the project-level SQL, an attempt to insert a row without providing values for these columns would fail. The two views were presenting different definitions of what was supposed to be the same table.
Most of the testing had been concerned with importing tables, extracting schema names, preventing duplicates and navigating between the individual tables. Although I had examined the SQL generated for individual tables, I had not paid enough attention to the SQL generated for the entire project. I also did not establish whether the changes had introduced the problem or whether it already existed.
When I started working on the SymPy problem, I was primarily concerned with the division by zero. Counting the calls to sin seemed like a reasonable way to make sure the fix did not interfere with the optimisation. From there, I became interested in expressions that appeared in conditions, then in nested conditions, and eventually in the order in which the printer emitted boolean operands.
I could probably have included all these cases in the initial description of the problem if I had been more familiar with SymPy’s internals. Much of what I wanted from the implementation, however, only became apparent while examining the generated functions. This is one of the things I enjoy about working with coding agents on unfamiliar codebases. I can try an implementation, spend some time understanding the relevant parts of the application, and gradually become more specific about the behaviour I want, rather than having to establish all of it before making the first change.