← Writing 10 min read

Two Python libraries, rebuilt with a coding agent

How I rebuilt pysqlx and samplepaths with a coding agent: what changed, how they are structured and secured, and how they compare with peer packages.

Two of my Python packages had been standing still. pysqlx, a small SQL library I wrote in 2022, had not changed since its first release. samplepaths, first published as pystochastic, is my fork of stochastic, a well-liked library of stochastic processes by Christopher Flynn that was last released in 2022 and does not install next to NumPy 2.

In 2026 I rebuilt both with a coding agent, Claude Code, doing most of the typing. I set the rules, chose what to build and reviewed every pull request; the agent wrote the code, the tests and the documentation, and ran the checks. This post covers what came out of it, how the libraries are built, where they stand on security and engineering practice next to their peers, and what I learned about getting useful code out of an agent.

The short version:

  • pysqlx went from version 1.0.2 to 3.0.0: four databases instead of one, every value passed to the database as a parameter, a security audit with three fixes, strict typing and about 140 tests that also run against real PostgreSQL, MySQL and SQL Server servers.
  • samplepaths went from its first release, 0.1.0, to 0.6.0: 68 processes, one interface for all of them, 3,182 tests, and Monte Carlo batches that keep pace with a Rust implementation while staying pure Python.

pysqlx: SQL databases without writing SQL

pysqlx describes tables, conditions and queries as Python objects, and a client turns them into the SQL of the database it is connected to:

from pysqlx import ClientFactory, Table

client = ClientFactory.get_sqlite_client()  # a database in memory

orders = Table(table_name="orders")
customer = orders.append_char_string_column(column_name="customer", size=50)
total = orders.append_float_column(column_name="total")

client.create(orders).execute()
client.insert(orders).execute_many(parameters_list=[("Ada", 120.0), ("Grace", 80.5)])
rows = client.select(orders, condition=total > 100).execute()  # (('Ada', 120.0),)

How it is built

The package has four layers, each in its own subpackage:

  • Structures (pysqlx.structures): databases, schemas, tables, columns of nine types, indexes, foreign keys and joins. Comparing a column with a value gives a condition, and conditions combine with &, | and ~.
  • Queries (pysqlx.queries): one class per statement, from Create and Select to Union and Reflect, which reads an existing table back from the database.
  • Dialects (pysqlx.dialects): turn a query into SQL. The base class implements what the databases have in common, so each dialect only states its differences.
  • Clients (pysqlx.clients): connect, run queries in transactions and return typed results. ClientFactory creates one for SQLite, PostgreSQL, MySQL or SQL Server.

The package has no required dependency. The driver of each database server, psycopg, pymysql or pyodbc, is an optional extra, so SQLite users install nothing else.

What the work changed

The 2022 version wrote the values of conditions straight into the SQL text. A name with a quote in it broke the statement, and a value typed by someone else could change what the statement did: a textbook SQL injection, in my own code. Version 2.0.0 passes every value to the database as a parameter, quotes every name, and keeps get_query_string() only as an escaped, human-readable view of a query.

Around that fix, the package gained PostgreSQL, MySQL and MariaDB next to SQLite and SQL Server, transactions, joins, aggregates with group_by and having, foreign keys, indexes and table reflection. Version 3.0.0 renamed the parts of the interface whose names did not say what they do, with a table in the changelog that maps every old name to the new one.

samplepaths: realizations of stochastic processes

samplepaths generates sample paths of stochastic processes as NumPy arrays: Brownian motions and their relatives, diffusions such as Cox-Ingersoll-Ross and Vasicek, jump processes, fractional processes, ARIMA and GARCH time series, multi-factor models such as Heston, Bates and SABR, and colored noise.

from samplepaths import GeometricBrownianMotion

gbm = GeometricBrownianMotion(drift=0.05, volatility=0.2)
prices = gbm.sample_paths_with_initial(n=64, paths=100_000, initial=100.0)

How it is built

Every process is a class in one of six family subpackages: continuous, diffusion, discrete, timeseries, multivariate and noise. They derive from two base classes, BaseTimeProcess for processes on a time interval and BaseSequenceProcess for those that evolve in steps, and share one interface: sample(n) for one realization and sample_paths(n, paths) for many. Anything beyond that has its own named method, such as sample_exact() or sample_hosking(), so simulation code can accept any process without knowing which one it is.

The rules of the code base are written down and enforced: one class per file, files under 300 lines, keyword-only constructors, parameters validated in property setters, and a docstring on everything public. The library depends on NumPy and SciPy only.

What the work changed

The mathematics of stochastic was kept; everything around it was rebuilt. The Python loops were replaced with NumPy operations, sample_paths() generates whole batches at once on several threads, and new families of processes were added, to 68 in all. Compared with the first release of the fork, a Markov chain of 4,096 steps takes 0.21 ms instead of 15 ms, and 100,000 Brownian paths of 64 steps take 6 ms on 14 cores.

Two promises hold it together:

  • Results for a seed never change. sample() returns the same values, bit for bit, for the same seed from one version to the next. A check in CI compares 490 seeded results with the last release on every pull request. A faster or better algorithm goes into a new method instead of changing an old one.
  • Results are checked against an independent implementation. For every process it shares with stochastic-rs, a package with a Rust core, samplepaths compares the distribution of 40,000 realizations with a Kolmogorov-Smirnov test, 43 comparisons in all. The first run found two processes that were wrong, both inherited from stochastic: the variance gamma process had a spread that depended on the number of steps, and the CEV process had the wrong drift. Both are fixed and documented.

Security

Neither library has been audited by an independent firm. What each has is listed below, so the claim can be checked rather than taken on trust.

Area pysqlx samplepaths
What could go wrong SQL injection, leaked credentials, unencrypted connections little: it reads and writes no files and opens no connections
Review an audit of the code in November 2026, with bandit, pip-audit and CodeQL, by the agent, reviewed by me no dedicated audit; CodeQL
Fixes from it three, released in 2.1.0 none
Code scanning CodeQL on Python and workflows, on every pull request and daily; no open alerts the same; two open alerts that two workflows do not declare their token permissions
Vulnerability reporting SECURITY.md with private reporting not yet
Releases PyPI trusted publishing, no stored tokens the same
Dependencies none required; Dependabot NumPy and SciPy; Dependabot

The audit of pysqlx found three problems after the injection fix of 2.0.0: values containing ; could add attributes to the SQL Server connection string, a SQLite database name such as "../other" could create a file outside its directory, and the SQL Server client logged a connection string that could hold secrets. Version 2.1.0 fixed all three and added a security page that says what the library protects against and what remains the job of the calling code, such as never building a column’s default value from user input.

Practices and design next to peer packages

Both projects follow the same engineering baseline:

  • uv and one Makefile: make check runs ruff, mypy in strict mode, the tests and a documentation build with warnings as errors, and the CI workflows call the same targets.
  • Tests on Linux, macOS and Windows with Python 3.11 to 3.14, on every pull request and daily; samplepaths also runs daily against the newest release of every dependency.
  • Every change through a pull request with a summary and a verification section, merged by squashing; the version comes from the release tag.
  • Documentation on Read the Docs with a guide, an API reference, a changelog and, for samplepaths, a gallery with an example for every process.
  • A record of design decisions and a roadmap in the repository, so a decision is not reopened without a new reason.

How that compares with the alternatives:

pysqlx. SQLAlchemy is the standard for database access in Python, with an ORM, a SQL expression language, many dialects and nearly twenty years of production use; if a project already uses it, it should keep it. PyPika builds SQL text and leaves running it to you. records and dataset are thin layers for running SQL or storing rows, and records was last released in March 2024. pysqlx sits between them: a small object model for tables and queries that also connects and executes, parameterized by construction, typed, with no required dependency, and tested against real PostgreSQL, MySQL and SQL Server servers on every pull request. It does not try to match SQLAlchemy’s breadth.

samplepaths. Its closest peers are stochastic, which it replaces; stochastic-rs, which has a Rust core and more models, plus option pricing and calibration; aleatory, which adds built-in plots; and solvers for arbitrary stochastic differential equations such as diffrax and torchsde. Against stochastic-rs it takes 0.5 to 1.4 times as long for 16 of 19 processes on batches of 100,000 short paths, and is faster for 7 of them. For a single realization, compiled code wins by a factor of 1 to 14. What samplepaths offers in return is a pure Python wheel that installs anywhere NumPy does, one readable module per process, and results that are reproducible on one thread or many. The project’s comparison page has the full tables.

Working with a coding agent

Across 33 pull requests, the two projects gained about 63,000 lines of code, tests and documentation, and the agent wrote most of them. What made the result trustworthy was not the model alone but the structure around it:

  • The rules live in the repository. Each project has its instructions for coding agents in .github/copilot-instructions.md, with a CLAUDE.md that points to it, a decisions page and a roadmap. The agent reads them at the start of every task and updates them in the same change as the work, so the next session, human or agent, starts from the same knowledge.
  • Done means make check passes. Lint, strict typing, tests and the documentation build run before any pull request, and again in CI on three operating systems.
  • Claims are checked against something outside the code. Bit-identical seeded results catch an optimization that changes numbers. The comparison with stochastic-rs caught two inherited bugs that the existing tests had accepted. Tests against real database servers catch what a mock would miss.
  • Numbers are measured, not written. Every timing in the documentation comes from a benchmark script in the repository, with the machine it ran on.
  • The agent proposes, I decide. It opens pull requests with a summary and a verification section and never merges; I review, squash-merge and cut the releases. The decisions with consequences for users, such as renaming the interface in pysqlx 3.0.0 or keeping samplepaths free of compiled code, were mine.

The agent was best at the work that is easy to postpone: a docstring on every public name, a test for every invalid parameter, a gallery example for every process, a changelog entry that tells users exactly how to update their code. It also found the SQL injection in my own 2022 code, which says as much about the value of a second reader as about the agent.

It needed the guard rails. Without the seeded-results check, a vectorized loop that changes the last bits of a result looks like a pure speed-up; without an outside reference, a wrong drift passes its own tests. The lesson I take from these two projects is that an agent raises the ceiling on what one engineer can maintain, as long as the project states what correct means in a form a machine can check.

Copyright © Bassem Girgis