A Python constraint solver fast enough for store work

NuCS 11.2.0, a pure-Python constraint solver accelerated by NumPy and Numba, just finished in a near tie with Choco 6.0.1, a Java solver with more than two decades of engineering behind it, on identical models. It won on the largest instances: 85 seconds against 120 on all-interval series at n=16000, and 14.6 against 17.9 seconds to prove infeasibility on Schur’s lemma. My first reaction was disbelief, then the thought that “Python is slow” has stopped being a reason to avoid solvers on client work. Yan Georget, who built NuCS, published the full comparison on Towards Data Science, complete with the exact command lines and result tables.

Where a Python constraint solver earns its keep on a store

Store work meets real constraint problems more often than we admit. Batching warehouse picks into boxes with the right mix and count is bin packing. Delivery slots with per-slot capacity and staff availability is scheduling. Deciding which backorders get a limited incoming shipment is an allocation problem, and the common fix, a sort followed by a foreach loop, quietly stops working as catalog size and order volume grow. At that point you want a solver.

My reason for never reaching for one was operational. The maintained open-source solvers live in Java, C++ and Python, and wiring any of them into a PHP site is a chore. “Python is slow” was a convenient excuse to skip the chore. The benchmark removes the excuse: with Numba compiling the propagators to native code, the same model ran at Choco’s speed, and the engine stopped being the deciding factor.

The article is honest about one cost that matters for us: even warm, NuCS pays a few hundred milliseconds of startup per process, visible as the roughly 376 ms floor on the smallest Latin square instances. That is noise for a long solve and fatal for a web request, so the solve belongs in a WP-CLI command, a cron job or a queue, with the result cached. I’ve written about running Monte Carlo forecasts for stock levels, and the rule there is the same: heavy math runs outside the request path.

A minimal wiring, no framework required:

<?php
// wp-content/plugins/bbioon-solver/includes/class-solver-command.php

class Bbioon_Solver_Command {

    public function solve( $args, $assoc_args ) {
        $key    = 'bbioon_solver_' . md5( wp_json_encode( $args ) );
        $result = get_transient( $key );

        if ( false === $result ) {
            $script = dirname( __DIR__ ) . '/solver/solve.py';
            $cmd    = 'python3 ' . escapeshellarg( $script )
                . ' ' . escapeshellarg( wp_json_encode( $args ) );
            exec( $cmd, $output, $code );

            if ( 0 !== $code ) {
                WP_CLI::error( "solver exited with code $code" );
            }

            $result = json_decode( implode( "\n", $output ), true );
            if ( ! is_array( $result ) ) {
                WP_CLI::error( 'solver returned invalid JSON' );
            }

            set_transient( $key, $result, HOUR_IN_SECONDS );
        }

        WP_CLI::line( wp_json_encode( $result ) );
    }
}

if ( defined( 'WP_CLI' ) && WP_CLI ) {
    WP_CLI::add_command( 'bbioon-solver', 'Bbioon_Solver_Command' );
}

The script reads JSON on argv, prints JSON, and the transient stops the next cron run from paying the cost again. On shared hosting you would swap the exec call for a queue worker, but the shape holds.

You might be tempted to answer this with PHP’s own JIT instead. PHP 8 ships one, and the release notes describe the tracing variant as about three times faster on synthetic benchmarks and 1.5 to 2 times on some long-running applications, with typical application performance on par with PHP 7.4. A JIT makes each unit of work cheaper without changing how many units there are, and in a search tree the unit count is the problem. Numba matched a JVM per-node, and the wins still came from the models.

Where the wins came from

On Latin squares, the plain model (one bound-consistent allDifferent per row and column) failed to finish at order 50 in both solvers. Both used the same consistency level and the same search strategy. NuCS then added a redundant model (two extra views of the grid linked to the first with channeling constraints, a few propagator loops in ordinary Python), and that model solved order 50 in 728 ms. The engine was the same in both runs, so the model made the difference.

Magic sequence shows the same pattern with cleaner numbers. Choco’s arc-consistent counting constraint was about 2.5 times faster at n=100. By n=400, NuCS with cheap count constraints plus two redundant ones finished in 942 ms against 1783 ms, and the article credits the second redundant constraint (a weighted-sum identity) with cutting the n=400 time from 2913 ms to 942 ms on its own.

That pattern is familiar from slow store code. A WooCommerce report that takes minutes is usually recomputing something in a loop that could live in a denormalized table maintained on save. I have fixed more slow store problems with a new table than with a faster runtime, and the benchmark makes the same argument at solver scale, with the bonus that remodeling in Python is cheap enough to try several times in an afternoon.

NuCS has a hard limit, and the article closes on it: every domain is a min..max interval, so propagators can only shrink bounds, never remove a value from the middle. That caps it at bound consistency, while Choco can run arc consistency over enumerated domains. On Golomb ruler that gap cost plain NuCS roughly 2 times, and closing it took a hand-written consistency algorithm (a few dozen lines of jitted Python). If your problem needs value-level pruning, budget that work or use Choco. If it doesn’t, NuCS installs with pip, ships under MIT, and its models are ordinary Python, which is why the remodels above were cheap.

I have not shipped NuCS on a client store yet, so weigh this as an interested outsider’s read of the numbers rather than a deployment story.

If you have a packing, scheduling or allocation problem on a WooCommerce site that your current loops can’t handle, this is the kind of work I take on: modeling the problem, choosing between a remodel and a solver, and wiring the solve into cron or a queue so it never blocks a request.

Spend ten minutes on it before deciding either way. In a throwaway venv, run pip install nucs, then run python -m nucs.examples.golomb -n 9 –symmetry-breaking twice. The first run pays the Numba compilation, and the second is the number that matters for a cron cadence. That tells you whether the startup cost fits how you would run it.

author avatar
Ahmad Wael
I'm a WordPress and WooCommerce developer with 15+ years of experience building custom e-commerce solutions and plugins. I specialize in PHP development, following WordPress coding standards to deliver clean, maintainable code. Currently, I'm exploring AI and e-commerce by building multi-agent systems and SaaS products that integrate technologies like Google Gemini API with WordPress platforms, approaching every project with a commitment to performance, security, and exceptional user experience.

Leave a Comment