Posts in C (20 found)
Unsung 1 weeks ago

“Duh, I thought everyone already knew this.”

One of the leaders in the popular game Civilization was Gandhi: = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/duh-i-thought-everyone-already-knew-this/1.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/duh-i-thought-everyone-already-knew-this/1.1600w.avif" type="image/avif"> But there was a problem with how Gandhi was set up, as described in the book Sid Meier’s Memoir! by the game’s creator: […] all of the leaders were given a score from 1 to 12 across a number of variables, and Gandhi’s military aggressiveness was placed at 1, as would be expected. A different piece of code, however, called for an automatic two-point drop in military aggressiveness whenever a country adopted democracy, which would theoretically have put Gandhi at a score of negative 1. But since negative numbers were impossible in this type of calculation, an overflow error caused the value to wrap around to the top of the number list, giving him a score of 255. Thus, the moment India became democratic, Gandhi would turn into a vicious warmonger and begin nuking everyone in range. A revision was quickly sent out, but players were so charmed by the hilarious juxtaposition that it became a running joke that has been thoroughly enjoyed and built upon by fans ever since. Images of Gandhi with captions like, “First they ignore you, then they laugh at you, then they fight you, then you cleanse them in atomic fire,” and “A nuke for a nuke will make the whole world bow down to me” have been shared far and wide. Other memes needed no words at all, like the photoshopped picture of Gandhi riding the falling bomb at the end of Dr. Strangelove. = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/duh-i-thought-everyone-already-knew-this/2.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/duh-i-thought-everyone-already-knew-this/2.1600w.avif" type="image/avif"> It’s a fun story and the 1 to 0 to 255 transition feels plausible, especially in the world still remembering Y2K. Here’s the kicker, though: But it’s not the countless callbacks and references that make the nuclear Gandhi story so funny to me. It’s the fact that none of it is true. The overflow error never happened at all. It is true that Gandhi would—eventually—use nukes when India was at war, just like any civilization in the game, and at the time this did strike a lot of players as odd. The real Abraham Lincoln probably wouldn’t have nuked anyone either, but the idea was that every leader draws a line in the sand somewhere. It’s also true that Gandhi would frequently threaten the player, because one of his primary traits was to avoid war, and deterrence through mutually assured destruction was an effective way to go about that. Since all leaders used the same basic diplomacy script, Gandhi’s reminder that “Our words are backed with nuclear weapons!” was identical to Napoleon’s or anyone else’s, and perhaps came off as a bit of a non sequitur from the humble ascetic. […] But at no point did a democratic score change, or any value approaching 255, come into it. That kind of bug comes from something called unsigned characters, which are not the default in the C programming language, and not something I used for the leader traits. Brian Reynolds wrote Civ II in C++, and he didn’t use them, either. We received no complaints about a Gandhi bug when either game came out, nor did we send out any revisions for one. Gandhi’s military aggressiveness score remained at 1 throughout the game. Meier seems to be annoyed by this, and does thorough investigative work in the book: Where, then, did it come from? The first reference appeared in July 2012—two years after Jon’s game, and more than two decades after the original game’s release—when a user named “Tunafish” added the supposed trivia to the website TVTropes.org, which can be edited by anyone. It sat, untouched except for cosmetic changes, until November of that year, when a watered-down version of the same story was added by an anonymous user to Wikia, […] Six weeks later, the spread began. First, two well-established users of a gaming forum repeated the story, with one of them citing the Wikia page after someone asked for a source. A few posts trickled out to other small forums over the next few days, again meeting only a single expression of skepticism, which was this time refuted with the TVTropes link. Things percolated gently for the next year and a half […]. The big break came in October 2014, when a comic called “Real Life Gandhi vs. Civilization Gandhi” was re-posted on Reddit. The comic itself was several years old, and only generically highlighted the humor of putting Gandhi’s finger on the button at all, but in the comments that followed, half a dozen users chimed in to share the story they’d heard about the overflow error. With that many in agreement, it became truth. = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/duh-i-thought-everyone-already-knew-this/3.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/duh-i-thought-everyone-already-knew-this/3.1600w.avif" type="image/avif"> Then, it was Kotaku, and Geek Dot Com, and eventually a popular website Know Your Meme that listed the bug as “confirmed.” Then: Six months after that, it was presented as a real-world example of an overflow error in the curriculum of a computer science class at Harvard University. Today, the story is still being revived on major news sites and message boards on a regular basis […] and almost always triggers at least a few replies of, “Duh, I thought everyone already knew this.” We talked recently about how makers of a mellow Japanese game were a bit perplexed by a bug in the game becoming an urban legend . We also covered some games that leaned into their bugs in their sequels . In the case of Civilization, the creators eventually leaned into… the bug that wasn’t. The lead designer of Civilization V, Jon Shafer, in the words of one Wikipedia editor “made Gandhi a nuclear weapon enthusiast.” The game was set up so that Gandhi’s internal “Build Nuke” and “Use Nuke” would always be maxxed out at 10 out of 10. As you can imagine, this did not help in squashing the myth. I’ll finish by quoting Wikipedia’s “Legacy” section: Despite its non-existence, “Nuclear Gandhi” is one of the most recognizable bugs in the history of video games. It has spawned a large number of Internet memes , and it has been used as an example of integer underflow in computer science courses at Harvard University , among others. The identity of “Tunafish” remains a mystery.

0 views
Max Bernstein 1 weeks ago

Inside PyPy: first contact with RPython

I get restless now and then and I want to implement a programming language. Then after mustering the resolve, I stew, for there is no good implementation language. 1 What am I to do, build my own programming language so that I can then use it to implement the first language? So I go back to modifying an existing implementation instead. There do exist established general-purpose tools for building fast programming language implementations: And more nascent ones such as Deegen , which was used to reimplement Lua. They each take different approaches: While none of these spark joy , they do each have benefits, including accomplishing the primary goal of offloading a lot of the language runtime choices and nasty details. In this post we will take a first look at RPython because it is the kind of VM implementor’s programming language that I keep thinking about. More on that later. Before we continue, please heed this warning: RPython is an implementation detail of PyPy. It has not had the years of polish that the rest of the system has had. Please do not badger maintainers. We’re going to build a little program in RPython. I am mostly following along with the docs , specifically Getting Started with RPython . There’s a little more ceremony than you might be used to and that’s because we’re going to run this file in two modes: normal Python 2 interpreter and compiled to C. This is the weirdness of RPython. If you don’t have installed, you can install PyPy, which helpfully still implements Python 2. If this all went fine, you will see it print . None of this is RPython yet . For that, we need a hint more ceremony. This is when we clone the PyPy project, in which we will find RPython. Now edit the Python program. Below the definition, add the following function: This function looks unused, but it is actually a hint to RPython: this is where the compiler should start translating. Let us now compile this program. Either inside the PyPy directory or with , run: If all goes well, you will see a whole mess of output, including a partially rendered Mandelbrot fractal. Finally, you will see something like: This is the RPython compilation process. In it, RPython is analyzing types, removing memory allocations, monomorphizing functions, and generating C code. Then it hands this C code off to a C compiler to compile. You should have in your current directory an executable named , which you can run like . It should also print . So far, this is not so different from Python. But let’s try something Pythonic. Let’s see what happens when we also use to mean string concatenation. Under normal Python 2, this will work just fine, printing and then . Under RPython, though, you get this inscrutable error (again, rough edges): and are unceremoniously dropped into the debugger, Pdb (hit Ctrl-D or type ). From this message you are meant to intuit that RPython did not enjoy that two different types flowed into the function. It helpfully tells you that there was a when trying to reconcile the and types that flowed into the function’s first parameter. It then gives you a pointer to the offending line and an IR dump. This happens because RPython requires function parameters to be monomorphic. Though the variables are syntactically untyped, RPython computes a type analysis to discover what type each variable should be. When and both flow into , boom, complaint. 2 To get around this, we do what all good C++ programmers do and we templatize the function. The RPython spelling of this is, as with many other features, a function annotation: You will find now that RPython happily compiles the program. This works because it makes a new copy of for every input type of the first ( ) argument. “Hey wait a minute,”, you might ask, “doesn’t this mean it stops being a valid Python 2 program?” Great question. No. You can still run the program as long as you provide the location of the RPython libraries via (as before): This runs ~instantly, which is a big relief. Developing an interpreter project with a 30 second or more turnaround time for each compile would be really frustrating. This has been a taste of RPython, both great and somewhat frustrating. I intentionally made it about RPython as a programming language rather than being so focused on RPython as a programming language implementation tool because I want some of its features to exist in a general purpose programming language… that then also might be used to implement other programming languages. I bring it up because I want to rehash the stuff that I occasionally grumble about in the vicinity of PLDI but for some reason have not written about online. Perhaps writing about it will encourage people. I think there is a lot of good stuff in RPython: I wish some stuff were different, or at least modifiable: I will probably add more to this list as I continue to remember some years of these conversations. Wouldn’t this be great? I don’t really have the time, energy, or expertise to build such a thing. There are so many design decisions along the way. It would probably accidentally grow to be huge and ossify along the way, and what a bummer that would be. If you have any pointers to existing projects or a way to implement such a thing in a really lightweight form (read: sub 10k lines, portable ideas), I would be very interested. Here are some pointers to other projects in the neighborhood: Thanks for CF Bolz-Tereick first for allowing me to talk their ear off about this for years and second for reviewing this post. I don’t want to implement atop Racket. C++ and C give me endless nightmares and are completely DIY. Yes, yes, I have built large VMs on C++ and C before. One time I posted so hard about the frustration that my tech lead unfollowed me on Twitter. I don’t really want to try to think about GC in Rust.  ↩ I initially thought any variable had to be monomorphic but I could not get an error from programs such as .  ↩ RPython, which has PyPy (Python) as its primary success story but also can claim Topaz (Ruby) and a couple of other smaller ones Truffle, which is the foundation of TruffleRuby, GraalPython, GraalJS, and even Sulong (LLVM) Deegen requires you to write your bytecode interpreter and type system in a C++ DSL. From this it generates an interpreter, a baseline JIT compiler, and, hopefully eventually, an optimizing JIT compiler. Truffle requires you to write an AST or (newly) bytecode interpreter in an Annotation-based Java DSL. From this it specializes guest language code before emitting Graal IR, which uses aggressive partial evaluation to generate optimized code. RPython requires you to write an interpreter in a restricted dialect of Python 2 that acts more like Java or Go than Python. The RPython compiler will then analyze your code, translate your “Python” program into C code bundled with RPython IR, and then “tier up” from the C code to JITed code at run-time. In order to go from “random RPython program” to “JIT compiler”, you need to participate in its meta-tracing , which requires annotating where your interpreter loop loops. Compile to native AOT with additional JIT. Seems like this provides good start-up performance with (optional!) tier-up as the runtime system observes the system’s behavior. Automatic memory optimization. There is no good way to syntactically express how an object should be allocated—Python is, after all, a very high-level language—so Python programs are profligate allocators of memory. RPython programs would be the same except that the AOT compiler does a whole-program analysis to try and remove these allocations. The JIT does too, but via a different mechanism. The JIT is provided to you. You don’t have to think about program analysis; the PyPy authors think about it for you. It is possible to do manual memory layout via so that you can write better data structures than Python would otherwise let you express. It provides a garbage collector for you. Furthermore, it handles all the stack scanning stuff and “oop maps” so you don’t have to build handles/ /… yourself. RPython does its partial evaluation and automatic JIT creation via meta-tracing . It is one of the last surviving tracing JIT compilers (alongside LuaJIT and, kind of, HHVM). For a lot of programs, method-based compilers seem to have produced better, or at least more predictable, results. I kind of want to see what a meta-method-JIT would look like. The user experience leaves something to be desired. I want better error messages, faster compiles, and less output. I want thorough docs. I want better performance feedback. This is in line with the rest of my ramblings about mechanical sympathy: the runtime should tell you what is wrong. I (or CF) shouldn’t have to stare at IR in traces and go “hmmmmm…” It requires writing a lot of your tooling anew. Even if I had, for example, a JavaScript parser written in Python, it likely wouldn’t be in Python 2 and it likely would not work well with RPython’s special rules. Runtimes such as JRuby get around this by compiling parsers (Prism) to WebAssembly and then bundling a WebAssembly interpreter written in Java. Along these lines, I would like more help with lexing and parsing, for which I have so little patience. I think it would be neat if it had a way to pause and save an “image” of the heap. After all, RPython is in control of all the memory and the code. It would be neat if, in addition to a JIT, it also helped you build an AOT compiler for your guest language. What if your language is statically typed? Should the toolkit provide functionality for type checking? Type inference? Some solution for C code. You can call it and stuff just fine but there’s no Sulong equivalent so it’s a totally opaque barrier to optimization. Don’t write your runtime helpers in C, sure, but at some point you have to interact with outside code. Weval, which turns an interpreter into a baseline AOT compiler. Its current implementation requires the interpreter to be compilable to Wasm and then its heap snapshottable with Wizer. One can imagine this technique being used instead to implement a JIT instead of an AOT, thereby also sidestepping the snapshot requirement. One might also imagine this applying to another IR than WebAssembly. Say, LLVM… semPy, which is an executable semantics for Python. Zig and other languages such as the more nascent k1 have the ability to run and generate code at build-time. Perhaps someone could implement a VM toolkit in one of these languages. I think a lot of the effort would still go toward something like GC handles if you want a moving GC. I don’t want to implement atop Racket. C++ and C give me endless nightmares and are completely DIY. Yes, yes, I have built large VMs on C++ and C before. One time I posted so hard about the frustration that my tech lead unfollowed me on Twitter. I don’t really want to try to think about GC in Rust.  ↩ I initially thought any variable had to be monomorphic but I could not get an error from programs such as .  ↩

0 views
Xe Iaso 1 weeks ago

"No way to prevent this" say users of only language where this regularly happens

In the hours following the release of CVE-2026-123633 and CVE-2026-123007 for the project NGINX , site reliability workers and systems administrators scrambled to desperately rebuild and patch all their systems to fix an HTTP/2 connection use-after-free during reverse-proxy processing when connection slots run low, alongside an HTTP/2 flow-control integer underflow that leads to an out-of-bounds memory copy over TLS, both of which can allow unauthenticated remote code execution on affected servers with HTTP/2 enabled. This is due to the affected components being written in C, the only programming language where these vulnerabilities regularly happen. "This was a terrible tragedy, but sometimes these things just happen and there's nothing anyone can do to stop them," said programmer Dr. Deontae Rempel, echoing statements expressed by hundreds of thousands of programmers who use the only language where 90% of the world's memory safety vulnerabilities have occurred in the last 50 years, and whose projects are 20 times more likely to have security vulnerabilities. "It's a shame, but what can we do? There really isn't anything we can do to prevent memory safety vulnerabilities from happening if the programmer doesn't want to write their code in a robust manner." At press time, users of the only programming language in the world where these vulnerabilities happen continuously were referring to themselves and their situation as "helpless."

0 views
daniel.haxx.se 1 weeks ago

Actual curl rewrites in rust

For a long time we have received repeated requests for, or questions about, a curl rewrite in rust. Often as a joke, but also seriously. A joke from years ago In this modern world of AIs, we have only been waiting for someone to prove it possible and now it seems we don’t have to wait anymore. This fall seems to be the time of the curl-in-rust takes as we first saw urlx appear a few months ago, claimed to be a memory-safe, from-scratch reimplementation of curl and libcurl and now in November curl, rewritten in Rust – a rewrite of curl and libcurl in Rust . This second one confusingly enough not even using a different name. This latter one claims to have spent 8,600 USD to make it happen. Writing code once was never the big deal with software and it still isn’t. Sure, it’s fascinating that you can make a set of agents accomplish this in only a few weeks but let’s face it: it could do this because all the AIs of the world have trained on curl code for years. curl is extremely well documented, there are hundreds of existing open source application using its API and there are thousands of test cases to verify the implementation. The C code sits there and all the AI needs to do is convert it to rust, then polish until the tests work. A know-it-all person’s comment from years ago curl is the result of time curl has come to be what it is thanks to many decisions, lots of time, many users, oceans of feedback and many iterations. Sure, recreating what curl is at any specific single moment in time is certainly doable. Doable, because we have made a perfect specification for that project. During the time these agents converted 185,000 lines of C code into 340,000 lines of Rust code (I counted), we merged over 300 commits in the actual curl project. We actually improved curl during these a little more than three weeks. A little over 200 bugfixes actually. 200 bugfixes that none of those rust rewrites have. We also fixed a few vulnerabilities. In another month we have done another 200 and maybe fixed a few more vulnerabilities. Will these clones keep up? The constant tweaking, fixing, improving and extending is what makes a software project live, what makes it attractive to users and what makes it able to compete with alternatives. That fixing, and occasional new feature, is a direct result of a working community of users, contributors and maintainers. That goes way beyond the source code or which language that is used. A primary reason it is hard to make a competing curl alternative is because of the development speed, the development team and the community around curl. It is not because of the chosen language it is implemented in. Only curl can boast decades of ABI and API stability and prove that we know this and can do it well – over time. An alternative that pops up today might be able to do it as well, and in a few decades we will know if they could . I know I’m repeating myself but: out of the 81 vulnerabilities we have confirmed in curl so far during 2026, 14 were the result of mistakes that most likely would have been avoided had we used a memory-safe language such as rust. That’s 17.3%. A Rust implementation of curl would thus still have had 67 of those vulnerabilities. I don’t believe in rewrites into any language. I believe in constant and never-ending polishing, iterating and refactoring. I should add that I have not been in contact with any of the people behind these rewrites, and if there are two I bet there are more that I just haven’t seen yet. I only know of them because people have pasted me links to their repositories. I don’t know what they will do with those projects going forward. Are they anything more than proof of concepts? I presume we will find out. They can of course follow along our commits and convert them to rust on the fly if they want – we only do about 11 commits per day on average. Or maybe they ignore the bugreports or maybe they take their projects in other directions? I wish them good luck whatever they decide! Several people asked me this. Imitation is the sincerest form of flattery that mediocrity can pay to greatness . / Someone I’m amused. A little puzzled. Fascinated. They spent their money and effort on that?

0 views
daniel.haxx.se 2 weeks ago

30 years of Internet transfers with curl

Thirty years ago, on November 11, 1996 the young Brazilian student Rafael Sagula posted the source code for his tiny HTTP download tool online. That was httpget 0.1: a little over 100 lines of C code. Bare bones source code with almost no error checks and limited functionality. When I found the source code of that initial httpget release just days after Rafael put it online, I had no idea how HTTP worked. The language to speak over the network to ask for resources. Okay, I already knew we call it protocol but not a lot more. I also had never heard of neither httpget nor Rafael before. I imagine that I found httpget by searching on Altavista since this was before Google, but I can’t recall the details. Seeing the simplicity of this code it was not difficult to immediately spot the fundamental basics of the protocol. I presume maybe in the same vain how countless others in decades to follow also have thought of it when seeing the details for the first time. Much later I would come to understand that to be an illusion of simplicity, but in those early days I was more amazed and fascinated. I already enjoyed doing network programming and HTTP reasoned with me at once. httpget 0.1 was almost completely without error checks and it used plain IPv4 addresses; no hostnames or URLs. I, still a naive and enthusiastic developer with an Open Source mindset (even though that term would not be established until 15-16 months later), addressed some immediate bugs I ran into and added name resolving to the tool. I made diffs and emailed patches over to Rafael; the standard way we exchanged code changes back then. I knew about RCS and CVS for version control, but the use of these tools was spotty. It would actually take until September 1999 until I adopted CVS fully for the curl project. We later switched to using git in 2010. The average internet connection speed of a normal household in Sweden, where I lived and I still live, in 1996 was 30 kbps. 30 kilobit per second. This was before v90 came and bumped the modems up to 56 kilobits. Ordinary mortals connected to the internet using modems over their single phone lines. Today, the average Swedish connection speed is 200 megabits/second. Thirty years ago there were just 36 million global Internet users and 250,000 websites. Compared to the 6 or 7 billion users and 1 billion websites of today. We used simpler protocols and while encrypted protocols like SSL existed, they were not used a lot and only for a few rare sites. Computers in 1996 In November 1996, my main home computer was still an Amiga 3000 powered by a 25Mhz 68030 CPU but in early 1997 I upgraded to a faster and more modern machine: an Intel Pentium 120Mhz. I ran Windows 95 on this thing, and its prime use was to run an X server so that I could connect to my work computers and pop up X11 terminals at home. I built the first versions of httpget remotely on SunOS, Solaris and Dell Unix – because they happened to be what we had running at work. I installed and tested Linux for the first time at work in 1997. I got our first public web servers up and of course I made sure curl worked fine on it. I did not switch to Linux on my home machine until 2000 when I also updated to an Intel Pentium III 733 Mhz box. In 1996 I was working as a software developer doing embedded systems and Unix development in C, for a small Swedish company called Frontec Railway Systems. While working there, I came to learn about and enjoy IRC , and in my spare time a few friends and I developed an IRC bot we called Dancer . Spare time developing a TCP client written in C. As the IRC bot slowly grew more capable, I wanted to use its extension capability and provide a currency translation service for the participants in the channel (the IRC term for a chat room ) . In an international channel like ours, we frequently discussed the price of things and having the bot able to quickly explain how much a hundred German Marks equaled in US Dollars could be a useful service. My currency service needed to update currency rates maybe once per day so that it could use decently accurate rates. I found an HTTP page listing a bunch of currency rates and the httpget tool for doing the downloads, and then the bot could offer up-to-date currency rate translations. All was good. I discovered computers and programming as a teenager on a Commodore 64. I got hooked immediately. I first learned Basic and moved on to 6510 assembler pretty quickly. In the late 1980s me and my friends had demo groups where we would write cool demos (and some game attempts) in assembler (under the group name Horizon ). I established my habit of spending spare time on programming back then. In the early 1990s I moved over to Amiga, started writing a text editor, got my first job at IBM where I truly got into a lot of C and Unix for the first time. Together with some friends we ran a BBS ( The Holy Grail ), for which we eventually would write our own BBS software; me and my brother Björn. I learned Motorola 68000 assembler on the Amiga. I wrote 8086 assembler on PC. I never attended university. I got my first computer job at IBM when I was twenty. I then thought I would take the uni route later, but I never did. I remain uneducated. In the early 1990s I discovered both the Internet and the world of freely available source code and I was hooked. Rafael was not terribly keen on dealing with my patches for httpget. I believe he mostly just put his code out without any particular desire to do anything more with it. Instead I became the httpget maintainer and kept polishing it. My main project was Dancer, the IRC bot. httpget was just a side-project to make sure the currency service kept working fine. At some point I fell over a gopher site that provided many more currency rates than the HTTP page I was scraping at the time so of course I had to add support for that as well to the download tool. With gopher support added, it was not just http anymore and the name of the tool was no longer accurate. It became urlget . A third listing was found that provided rates over FTP and, yes, I added support for that protocol as well. Already from the start I made the source code available under a free license, continuing what Rafel kicked off. He hosted the first releases, but during 1997 I took over and hosted the tarballs on the website I set up and administrated for work. I told my friends and the news about the tool slowly spread. I started getting bug reports from users and occasionally someone sent me patches to fix problems or add features. This was a time of many Unix flavors and as I wanted widest possible use and adoption, I knew that I needed help and assistance from friends to make sure it built and ran fine on all those different systems. In the beginning of 1998 I added upload support to the urlget tool (both FTP upload and HTTP POST) and again I realized the name of the tool was wrong. I decided I should try a name that contains the word URL, that can be pronounced in English and that is easy (and short) to type on a keyboard. cURL it was. The leading ‘c’ could be short for client but I also liked that the name could be pronounced as see URL , as the tool would display the resource at the URL. You would see it (in a terminal). Naming things is hard. curl 4.0 was released on March 20, 1998. By then it had grown to 3,300 lines of code and it featured 24 command line options and it spoke three protocols. Gradually I lost interest in the IRC bot and the currency service but I stuck with curl. People used it, I got feedback, it improved. I started and participated in several other Open Source projects, but curl remained my main baby and focus. The concept of a function library that offers useful functionality to other programs is a concept I learned already on my Amiga days. As an example, I wrote the scripting language ( FPL) for our Amiga text editor ( FrexxEd ) as a library, and we could later use that language for our BBS software, FrexxLink (which ran on OS/2) as well as in Dancer, the IRC bot. A library is sort of next-level cool: not only is the source code available for everyone, but the functionality is as well; in an easy-to-use way. The idea of converting curl into a library was already in the back of head from the start and in the summer of 2000 I refactored the internals and in August that year we introduced the first ever libcurl. Maybe someone else wants to do Internet transfers in their services or tools? Turns out some did! One of the first adopters of libcurl was the PHP language which almost immediately decided that libcurl would become their default internet transfer engine. Being a key component and therefore part of their success journey helped getting users, getting testing, bug reports, feature requests and making the library solid. curl is a child of the 1990s. Back then there were not a lot of options and language alternatives if you wanted to write a program that would easily build and run on most available operating systems and CPU architectures. Sure, C++ maybe could have been an option but I never liked it – and I still don’t. I’m also a strong believer in continuous and non-stop improvements and iterations; not rewrites. curl was never rewritten and if I get my way, it never will be. We do however repeatedly refactor and rearchitect internals to adapt to a changing world. I wanted curl to be usable by everyone on every machine so it was designed and written for that purpose from the start. The source code in a portable way and the license in a liberal way. We did most things wrong at the beginning but we learned, adapted, tried again, iterated and we kept doing release after release. Gradually we learned and did better. Every release with lots of bugs fixed and often a few new features. I kept spending my spare time on curl. Every day, every week, every year. Given enough time, something great can grow. I did my first twenty-three years of this journey with curl only as my hobby. While curl happened, life also happened in parallel. I have switched jobs many times. I got married, bought a house, got two kids, and saw the kids grow up to be amazing adults. Somewhere in there I also managed to convert my hobby into my full time job. Living the dream. curl is my life. My life is curl. I have been invited and able to speak to audiences hundreds of times in a dozen countries. I have received multiple awards and even gold medals straight from the hands of royalties for my open source work. I don’t have an end goal with curl and I never did. I just want it to do internet transfers the best way possible: fast, securely, using the proper protocols in optimal ways. There is no rush towards anything. It is just a non-stop walk forward with never-ending polish and tightening every bolt there is. Thirty years have flown by and yet the development pace is still intense. We regularly implement new transfer protocol features before anyone else. We have leading implementations for lots of network solutions. We ship code that carries a huge portion of the world’s internet infrastructure on its shoulders without fuss. I still enjoy building things. Writing code to create something that did not exist before; and maybe even more so to make the program actually do things users want and like. I enjoy fixing bugs partly for that reason, but I also like the puzzle and the challenge of debugging and solving tricky problems. Designing a software architecture, coming up with APIs and figuring out how to provide powerful network transfer functionality to power billions of devices are things that make me eager to get started again every morning – still after thirty years. It never really gets done. The world of the Internet and its transfers keeps changing. New protocols, new versions, new flavors, new third party libraries, new build tools and environments force us to constantly change and adapt.  I want curl to be a leader in internet transfers, its protocol implementations and every aspect of the project. I want us to be an exemplary Open Source project and run every tiny piece of it in an almost excessively transparent and progressive way. curl should be a top contender for the most-secure software component you can find. Our project should be friendly and welcoming to newcomers, both users and developers and not the least, there can be no other software project to compete with the amount, the accuracy and the plethora of documentation. Not to mention that we never break APIs or ABIs. Applications and scripts should be able to keep running, unmodified, even when they upgrade curl. Until the end of times. I’m a firm believer in iterating and never rewriting. We fix, we refactor and we clean up but rewriting into another language or even using the same language is out of the question. Simply put: software engineering done right. While curl speaks more than two dozen protocols (at least counting URL schemes), it has always been most known for HTTP(S) and I think we put the most work and efforts into its HTTP engine. We know lots of people use curl for debugging HTTP in general and their server implementations in particular. We were early adopters of both HTTP/2 and HTTP/3. We are often told people use our way of speaking HTTP and our source code as guidance for how things should be done. This is an honor and a huge responsibility that we take seriously. After I first had learned about HTTP from reading httpget source code and then of course studied the RFC documentation explaining the specifics. In the late 2000s I learned about the HTTPbis effort and joined the mailing list for the HTTP specification update in the works. In 2009 I participated in my first ever IETF meeting that took place in Stockholm, Sweden. There, I got to meet some of the HTTP RFC authors and main people for the first time: Roy, Larry, Mark, Julian etc. They are all lovely people and I really felt that I would be able to make curl better by hanging out in the HTTP IETF circles more. I also wanted to contribute back my own experiences and viewpoints to maybe help improve the world ever so slightly. That community later started the HTTP Workshop series out of which I have been to every single instance. Hanging out with the primary HTTP implementers in the world is fun, super educational and humbling. I believe this networking makes HTTP and all the involved  implementations even better. curl is not a legal entity or a formal organization of any kind. It is a bunch of loosely connected people on the Internet who have a common goal, a few mailing lists, a website and some git repositories. curl is not hosted under any umbrella, not part of any larger organization and is not owned or controlled by any company. It is probably as free and independent as a software project can be. I believe this is an excellent position for curl and gives us maximum flexibility and control of our own destiny. libcurl runs in an estimated thirty billion installations today. It is a rough estimate since the majority of all libcurl users never tell us they use it, but we need to find it mentioned in their credit screens, open source license windows or their manuals. A super popular app might use libcurl today and not tomorrow, or vice versa, which can make the numbers shift by several billions overnight. In reality of course, once the pulse raise has calmed down and your ego is content, these numbers do not matter. In our corner of the world, things don’t change notably when we go from a thousand installs to billions. We still work with similar people, in similar ways, with similar challenges. For me, and for many others, the coolest place curl has been used is probably on Mars. It was confirmed by NASA that curl was used to aid the Mars landing mission, even if they don’t tell us exactly for what and where. A ridiculously common question to me is “what is the weirdest place you’ve seen curl run?” I have ceased getting surprised about what devices and what things that are Internet connected and thus where curl runs. Light-bulbs, dish washers, AC units, heat pumps, cars, printers, blenders, ovens, toy robots, drones, guns, motorcycles, medical devices, fridges, soundbars and espresso machines. Of course in addition to all those “traditional” things we already expect to run curl: games, servers, cars, printers, TVs, watches, tablets, game consoles, blue-tooth speakers, routers, mobile phone apps and their operating systems. Our modern society is keen at eventually making everything network connected, and once they are, they can use curl and libcurl to perform their transfers. Benevolent Dictator For Life. A term popularly used to describe the steering mechanism of many Open Source projects. Basically a single person being the captain of the ship. The one who can commandeer the direction, who can dictate truths about the project and who says yes and no firmly. For better and for worse, I remain the BDFL for curl. I try to repeat that curl is not a solo-show and it was never a one-man circus. We are literally thousands of people who have contributed code, and every year there are hundreds of new authors helping out. I may remain the captain of the ship, but no ship above a certain size can be managed without a lot of additional man power and curl is no different. I may very well remain BDFL for a long time to come because I love my role and because I don’t know any other way to live my life or to run the curl project. There are no succession plans and I am against doing such. There is no heir or vice-BDFL prepared to take over. Instead we document everything and every detail so there are no secrets, so that no formal hand-over should be necessary (except for some rare passwords). If I get run over by a truck tomorrow, you guys can figure it out and continue. You don’t need me. My email address is commonly listed in the regular curl license and this license is usually included in license listings, credit screens or manuals. When random people run into problems or issues with products in this modern society, they often struggle to find someone to help them. There is no one to contact or ask. My email then sometimes serves as a last resort to finally get the answers they’ve been fighting for. I frequently get emails about products I never knew existed, I certainly didn’t know they used curl and I for sure don’t know how to help the users with their problems… The much darker side of the traces curl usage leaves in products, is when malicious tools, services and attackers use tools that can be associated with me and my email address. I have been accused of various attacks and “hacking” people and companies multiple times. I have received death threats multiple times and I strongly suspect that my US visa problems were triggered by something in these veins. I stick to the Open Source ethos and spirit. It is a fundamental part of my belief system and I am convinced this is the superior way to produce software to build society on. I do everything I can to stick to the liberal license curl is shipped under because I love the concept. It is however not an easy pitch: give everything away for free and then try to get someone to pay for it. I think it is fair to say that if I wanted to optimize for money, I should have played this one out differently. That would have been another life. Not my life. Of course I feel immensely proud of what we have accomplished . The little toy thing in 1996 kicked off a journey that led to the creation and continued maintenance of a modern Internet infrastructure cornerstone. We have reached this point, not by talking, not by using marketing nor by tricking someone into using our code. We conquered the world by shipping consistent top quality over several decades. curl runs in all these devices and services done by all those companies because it is the right choice for them, selected because it is Open Source, rock-solid and fast – and also likely to be around in the future. Everyone can depend on us to keep shipping updates in a proven stellar fashion and minimal friction. Forever and ever. There are many dimensions of the future to consider here. The future of Open Source. The future of curl. The future of internet transfers. The future of the C programming language and the future for me, personally. At least. I don’t think I can guess the future any better than other humans. I was never good at it and I never really tried to. I always only focus on the next coming months and make quick adjustments when things make turns . I think Open Source is a solid way to do foundational software, now and in the future. It will continue to have a funding problem and too many projects live and die with a single maintainer. But building common and open building blocks is simply a requirement for speedy development, for building reliable components and for being able to produce products and services at the speed we seem to want. I don’t believe AI will kill Open Source. I think curl has many more years of service ahead. Primarily because it is the trusted solution and nothing else is even close to this long proven track record, secondarily because it runs on all platforms like no alternatives. I do not rule out that it will be replaced by an alternative at some point, when projects written in C are gradually phased out. (If they ever are.) Internet transfers in general seem like a fundamental idea that probably is going to be around in a similar style for a long time. The protocols will keep evolving, changing and getting updated but the client/server/protocol concept seems solid and likely to be here for the long term. I personally will keep working on curl and Internet transfers for as long as I think it is fun and challenging. I turn 56 years old in a few weeks. I hope to be able to spend several more decades on this. Thank you mom and dad for your understanding and supporting attitude when I as a teenager got completely sucked into a world of computers and programming. Thanks Björn and Kjell for all the awesome times and all the fun when we learned development together and took our first stumbling steps as programmers. Thanks to the Horizon team for the fun and all the demos, copy parties we did and attended. Thanks to Huddinge Vi Unga who owned the machine and sponsored the dual phone connections for our BBS for several years as we discovered fidonet and a world of people and communication. Thanks Jonas for getting me that first job at IBM when I had no work experience at all. Thanks to Bjørn for co-creating the Dancer bot project with me to the people in #amiga IRC chat on Efnet and then IRCnet for your support. Thanks to my bosses at Frontec in the mid 1990s who allowed me to do spare time development on their various Unix machines (even though you probably were not aware of the full extent). Thanks to all the early users and adopters of curl who pushed me forward and who brought it into all the important Linux distros early on and showed me this thing had legs. Thanks Anja, my wife, for keeping up with me spending all this time in front of my machines, and for sometimes boring you to death rambling about some miniscule detail from the curl project that I couldn’t let go from my mind. Thanks to my kids Agnes and Rex for being the lights of my life, for being awesome and for not being particularly impressed by or interested in what I do. You do your life. Thanks to everyone who ever contributed to the curl project, in whatever capacity. In particular, thanks to Stefan, Viktor, James, Viktor, Dan, Jay, Daniel, Max for being part of the core maintainer team for ages. Thanks to Björn, Kjell and Linus of Haxx for being awesome friends and always supporting me and curl whenever it has been needed – and for the Rockbox side-adventure of course. Thanks to Larry at wolfSSL for believing in me and curl enough to allow me to work on curl full-time without even blinking. Thanks to all curl sponsors, donors and to all awesome paying customers of curl support, who combined are what makes it possible for me to do what I do. Thanks to everyone who ever invited me to conferences and events to talk and meet people. Thanks to Patrik who nominated me to the Polhem Prize award that I then received in the form of a gold medal. Thanks Michael for nominating me for the IVA gold medal. Thanks to all others whose names I forgot to include here. Thanks to everyone who uses curl and continues to participate in curl development. Yes. We have two separate birthdays: httpget was born in November 1996. curl was born in March 1998. Rafael Sagula unfortunately left us much too early. He died in 2016. I am grateful for him kick-starting this thing for us.

0 views
danluu 1 months ago

“We should be more ambitious with the software we build”

Since early this year, Michael Malis (of pgrust ) has been showing me interesting things he's done and saying [W]e should be more ambitious 1 with the software we build There is, understandably, a lot of skepticism about projects like pgrust because there are so many low-quality AI-generated projects out there. If I didn't know Malis and didn't look into it, I would just assume that pgrust was another vibe slopped project that's never going to work. But I know Malis well enough to trust his work without looking into it, and if you look into it a bit, you'll see that in testing pgrust, he's testing thoroughly enough that he's even uncovering real bugs in Postgres, such as this numerical bug that can cause valid SP-GiST operations to fail , this format cache bug that can cause incorrect results from JSONPath , this pgcrypto bug that can cause later operations to fail , multiple memory safety bugs in the dictionary loader 2 , this money overflow bug , etc. This isn't to say that pgrust is bug free 3 , but it does indicate that there's a substantial amount of testing happening and, even if pgrust itself is never successful, just making the attempt will have improved Postgres in a durable way. The main pitch for pgrust is actually performance, and that's where the really interesting work is happening; if pgrust fails, it's possible that some of the optimizations they've demonstrated will make it into Postgres, Clickhouse, etc., but that's obviously less direct than filing Postgres bugs which get fixed. That being said, I find it understandable that, every time I see pgrust discussed on a news aggregator, most people dismiss it as vibeslop garbage because almost all of these rewrite projects are slop. If I didn't know Malis, I would make the same assumption, because who has the time to look into all of these projects? Because I know Malis, I didn't bother to look at it; I just trusted him (I only found the above because I wanted to check on pgrust before using it as an example for this post). As a consumer of software, everywhere you look, there's slow software that the creator is claiming is fast because the creator is touting some slop benchmark, e.g., here's one of multiple examples I saw yesterday , and of course low-quality software that doesn't work is more common than ever. But, as a builder of software, it doesn't matter that almost all of these projects are vibeslop, that other people are out there shoveling out huge piles of crap and calling it gold. You can build things like pgrust or other projects that would've been too large to really be feasible in the past and, if you do a reasonable job with testing and benchmarking, that stuff can actually be good-enough quality to use. If I were writing it, I would say "we can be more ambitious with the software we build" and not "we should", but Malis has been casually chatting with me when he's said this, so maybe he would say the same in an actual post; don't read too much into should vs. can here. What's interesting to me is how capabilities have advanced such that we can do a lot more. Just for example, after hearing that OpenAI was going to use Cerebras for their SOTA models and not just fast-but-low-quality models like 5.3-Codex-Spark, I looked at where time on my computer would go if I was using a SOTA model, but 10x to 100x faster; some things that were already sometimes a bottleneck that would only get worse with a faster model were: At the level of a "works for me" project, these are all things that can seriously be improved. I don't have much spare time at the moment but, even so, I built this regex engine that can be tweaked to be faster than other general-purpose regex libraries on any particular workload I care about , this ripgrep fork that uses the native code compiler from the regex engine and is faster for my codex ripgrep workloads (of course a text index is the better solution, but I've already worked on text indexing and this was a "just for fun" project where I wasn't trying to do the optimal thing), and a Rust that sped up builds for my projects (huge improvement for cold builds, moderate for warm, limited by wanting to avoid forking the Rust compiler front-end). For syscalls and filesystem overhead, just switching development from Mac to Linux improved this a lot, and of course this is another thing that can be sped up a lot as well, especially when agents are hammering lots of small filesystem operations (it's not uncommon to see my machine waiting on filesystem ops because the standard OS filesystem interface wasn't designed with modern disk performance in mind). With modern disks, there's no reason to use the *nix filesystem API. In the past, writing a developer toolchain that uses direct I/O instead of normal filessytem operations would've been an absurd endevaor, but that's totally doable now. For someone like me who doesn't know anything about regexes, string matching algorithms, compilers, interpreters, etc., this set of projects would've taken a year or more to get to "works for me" quality. Instead, this was a low single-digit number of hours of my time. If I wanted to make any of these things meet a "useful product or open source project" quality bar, that would be a lot more work 0 , but it's still pretty incredible how much this process is sped up. My read of Malis's meaning when he says “we should be more ambitious with the software we build”, is that it doesn't even occur to people to do these things that are now easy. For weeks, every time I logged into Twitter, I saw someone complain about how Rust compilation is slow and is limiting development velocity (I think this wasn't actually true when I saw the complaints, in that this was before 5.6 Sol and 6 Astra were available on Cerebras, and if you measured where the time actually went, Rust compilation time wasn't actually that much of a bottleneck at the time). Sure, Rust compliation is slow. You can just write a Rust interpreter as well as speed up compilation directly. There are problems like this which I see people complaining about daily that are solvable without a lot of time or effort now. As far as I can tell, these problems are problems because people are implicitly carrying around a pre-agentic cost model. Ten years ago, the kind of person who implemented a new compiler because their compiler was slow was the kind of person who started programming a new 3d game engine when they wanted to make an indie game, i.e., the kind of person who never ships anything. Most productive programmers I know still have an aversion to this kind of thing, even though it is now actually reasonable to implement this kind of thing now 4 . Another project I previously mentioned was this Azul AI which is superhuman at matched time controls . When I did that (with GPT-5.1/5.2), with zero AI knowledge, it took about 5 hours of my time to get something superhuman, and about 20 hours of my time to become what appeared to be the strongest AI at the time, including being stronger against humans than this AI that was used to cheat on Board Game Arena . Gabriel Cangussu recently built an AI that demolishes my AI, and AFAICT, it took him substantially less time than my AI took me. From talking to him about it, one key difference is that Fable 5.1 and Opus 5.5 have a much better understanding of board game AIs. When I used GPT-5.1/5.2, pretty much every suggestion they had was wrong and I had to do a lot of steering to get things to be remotely reasonable. If I had GPT read a codebase or a paper to implement relevant techniques from the paper, it would fail. If I read the paper myself and named a technique, it would say it did the technique, but it would generally do something that superficially looked like the technique but wasn't the actual technique until I issued some corrections. When the model is that far from being able to do the right thing, if you have no background in the area, it's fairly time consuming to check if the model did the right thing since you have to learn enough about what it's supposed to do to be able to check that it did what was claimed. When I did that project, I said to friends that I didn't think the state models were in could last. It seemed impossible that they wouldn't get good enough to be able to read a paper and implement the techniques soon, and it seemed like they should also be able to pick out codebases and papers to crib from as well. From my experience messing around a bit with Fable 5 and Cangussu's experience with Fable 5.1 and Opus 5.5, that seems to have happened, which is a huge time saver for someone like me who doesn't know anything about board game AIs (I know a little bit now, but still less than any real AI researcher) 5 . For any particular domain, like board game AIs, you can say, "who cares? Board game AIs don't matter", but I've found this increase in capability to be true in quite a few different domains. Just for example, I did this toy eval of verification and test techniques with GPT-5.6 Sol implementing zstd on medium and xhigh . I haven't had time to write it up, but when I published that post, I also re-did the evals with GPT-6 Astra. 6 Astra was so good that I had to find different evals because models had advanced too much. For zstd, 6 Astra succeeds at passing all of the registered tests more than 99% of the time across all conditions, even the ones that significantly impair performance, like using TDD (and, BTW, it does it more cheaply as well, taking about $1 to implement zstd). I ended up using the IMAP RFC, which 5.6 Sol couldn't do effectively, and Pandoc, which is a pretty major thing to implement as it needs to be able to read and write many different formats 6 . BTW, when people have said they used the new model and everything just works, software is solved, etc., I haven't found this to be true at all. It's true that there are a lot more things the newer model can one-shot, where things basically just work, but this just means that I end up working on more ambitious things where models still struggle 7 . I'm more productive and can work faster , but I find that, in terms of what I'm doing, I get farther from "it just works" with each more capable model because the gap between what the model can verify effectively without significant handholding and what the model can implement has been increasing 8 . All of that is a long-winded and less eloquent way of saying: we should be more ambitious with the software we build. Thanks to Laurence Tratt, Yossi Kreinin, Alex Kolovsky, and Michael Malis for comments/corrections/discussion. I've had this note on my recent posts, which also applies to this one. In order to get more posts out, I'm trying to crank posts out in half an hour and not review them much. This definitely means less well-supported posts. If I were writing this in my standard style, I would've had comprehensive benchmarks for all of my projects that I mentioned. Instead, I did a quick comparison that satisfied my curiosity and am writing this up without rigorous benchmarking, and there are maybe twenty or thirty things in this post that I'd like to do but haven't done. I haven't even written up this Rust interpreter. If, five years ago, I'd cobbled together a Rust interpreter that got a 50x speedup on cold compiles and 2x on warm/cached builds (with much more being possible if edits to the Rust compiler were in bounds), that woudl be a super interestin thing that I'd want to write up, but even operating in this mode where I barely edit posts and just blast them out, this isn't interesting enough to write up because it's so easy to do things that would've been considered very interesting not all that long ago. Here's a comment from Yossi Kreinin, quoted (with permission, of course): If you publish this I will publish a response explaining that for most people they should be less ambitious with the software they build with AI or they'll experience abject failure. I think a lot of the problems don't lend themselves that well to "agentic loops" since you don't have clear pass/fail criteria, and even when you do most people have trouble reasoning about giant black boxes which they can impose constraints on but can't understand the innards of [I include myself in this set.] This is a little bit like microservices I guess, where some people both need it and are very good at using it but likely for most people, they need it less and can't use it well at all. I sort of envy the ones who should and actually can be this ambitious about the software they build of course; not saying you shouldn't be more ambitious at all but moderating said ambition is a big part of handling the current situation for most I think I have a similar thought about " there's no reason for software to be slow " BTW; in many cases, if you use AI to speed up some flow, you will add a bunch of messy code that will be overfit for the use case you tested on and will neither generalize, perf-wise, for all the use cases you should care about, nor will be maintainable upon future changes. If you know what you're doing and you understand how the system should be decomposed into parts and when it makes sense to go all-in on optimizing some part or a combination of them working together and how to properly benchmark it, etc., then things are great, but if for instance you have a manager who thinks there's no reason for software to be slow and he pushes people to use AI to make random parts of the software fast... Run for cover My feeling is that, overall, the situation here is a bit analogous to the discussion here about why I don't like when people talk about how AI gives a 100x or 1000x productivity increase . There are some things that are sped up by a very large factor, easily over 1000000x. And some things don't currently get sped up at all. If you do exactly what you would've done five years ago, but with AI, the speedup is fairly poor because of Amdahl's law . But, in the general case, you can choose what to speed up and if you're looking for things that are productive to do, this often seems to involve things that were previously too expensive to do. And, I think that you can often set up systems that have some kind of self-checking property even when most people wouldn't. This discussion of the implementation of Guards of Atlantis 2 is an example of that. It's a poor choice for an AI project because the official rules are a mess of ambiguous and contradictory English text (it's probably the game I've seen humans misplay at the highest rate, and the rules are confusing enough that the designer has often changed their mind about what their own rules mean despite continually maintaining that the rules are perfectly clear and one can play the game by simply reading the rules as written). If you try to produce a working set of rules in a naive way, AI won't really help with this (although it can speed up implementation once you have a clean spec), but for that, I was able to set up some kind of janky set of consistency checks between all of the inconsistent explanations of the game rules, which got fairly close to a correct set of rules (approximately as close as what someone else did with much more human effort and less of a systematic approach), which was enough to compare it to someone else's implementation and get a working set of rules. This setup did cost a lot more in tokens than a more manual approach. But it was "only" a month or two of the $200/mo OpenAI subscription with GPT-5.1/5.2, which is a lower cost than the cost in time of me sitting down and writing a clean spec for the game, i.e., a copy of the rules that is actually consistent and correct. I feel like a lot of problems are in something like this class of problem, where it's possible to set up some kind of at least partially self-checking setup that a human can spend a small amount of time on. This also feels analogous to the situation about software testing at large, where (before coding agents) I found fuzzing and property-based testing to be highly effective. For most domains, people told me some kind of reason this kind of testing wouldn't work, but when I've tried these techniques with all of the domains people told me these techniques don't work for, they work fine. They're somewhat more work to apply, but they're still applicable and, AFAICT, more efficient and effective than writing traditional unit tests. Part of the gist of Yossi's comment is that people aren't doing this kind of thing. Considering how many more bugs I see now than I used to, e.g., the last time I opened up the web chat for a big AI lab, I ran into a double-digit number of bugs within one minute, it's hard to say that Yossi is wrong. But, to that point, I still have my original opinion. Just because other people are pumping out vast quantities of barely working slop doesn't mean that you have to do the same thing. The examples in the body of the post I gave for things I've done are tooling things I never would've done. There are a lot more things like that as well since it's so easy to build "works for me" quality tooling that's intended solely for me. I do think it's possible to go further than is productive, e.g., Steve Yegge wrote a lot about Gas Town and how productive it was, but when he was building his next agentic framework, he noted that he never used Gas Town to successfully build anything other than Gas Town , people were into Ralph Loops for a while even though, when I tried comparing them, they seemed worse than just doing the naive thing I was doing at the time, normal loops with context where you sometimes clear context as appropriate instead of doing it by default at the completely arbitrary point of when a single turn is completed , etc., so I've tried to stick to things where the impact is pretty direct. Besides the obvious reason this has been effective, the dramatic change in model and harness capability over time means that what tooling it makes sense to build changes very quickly, so spending a lot of time working on any particular tool that will be suboptimal at best and quite possibly obsolete in three months doesn't really make sense. And, for a lot of my personal tools, my assumption is that an AI lab will obsolete anything I make in short order. For a very silly example of this, I have a tool that was useful since the release of GPT-5.6 Sol that restarts codex when it finds a memory leak. Presumably, OpenAI will fix this at some point and this tool will become worthless. For a slightly less silly example, take the Rust interpreter I had some agent build. For token-budget reasons, a lot of things that ought to be done for a very high-performance interpreter haven't been done. For example, the interpreter doesn't modify the actual Rust front-end compiler to make it easy to take updates; performance would be much better if I just made changes to the Rust front-end, but I don't have the token budget to maintain a compatible fork of the Rust compiler, but this shouldn't be a problem for OpenAI. OpenAI spent $10B+ on getting access to Cerebras while also preventing Anthropic from having access. Funnily enough, for coding, on many tasks, if you actually use one of their SOTA models and compare it to what you get from Anthropic, the actual speedup isn't all that large because of time spent on things like compiling Rust. Given that they were willing to commit $10B+ on this, it stands to reason that they'll eventually do a better job at speeding up the relevant tools than anyone could feasibly do outside an AI lab, so there's not much point in spending too much effort on this (this could arguably be untrue if non-coding tasks are expected to completely dominate future OpenAI revenue in the short term, but even then, given what they pay for tokens vs. what I pay, it still seems like it would make sense for them to speed a lot of these things up given that I could do it outside of a lab; perhaps there's some kind of argument like, if you have access to their usage data, there are so many more important bottlenecks that this one doesn't make sense to prioritize, but it still seems like it should make sense for them at some point even if it doesn't fall into the top 100 bottlenecks for Cerebras-enabled coding agents). Another kind of thing that one might not call ambitious, but that speaks to the kind of thing that's possible, are games that I've made. There are games I've thought about and wanted to make that I don't think are generally enjoyable enough that they make sense for a real audience, but that I've wanted to play. For example, ever since reading David Gerrold's Star Wolf books in the 90s, I've wanted to play a game that implements combat as described in the books, which is a sort of like submarine combat. At least among realistic war games, this genre is extremely niche because almost everybody finds naval combat boring, and submarine combat is a particularly boring subgenre of naval combat games, so this doesn't really make sense as a money-making game, but it's so easy to implement games that I had an agent implement the game so I could play it for an hour or two. I never would've spent 10-20 hours implementing a game so that I could play it for an hour or two, but I'd spend 5 minutes. I've also previously mentioned implementing a game with the same rules as Scout and Guards of Atlantis 2 . I was never going to take the time to implement these games by hand just so I have a way to play with my friends on the occasions where we can't get together in-person, but I'm happy to have an LLM bash these things out. And, of course, for people who want to make games with a wider audience, there's a game renaissance going on right now due to coding agents. It's pretty amazing how many interesting and creative games are being made now that having programming skills and the time to put them to use is no longer a bottleneck for making games. Data analysis is another thing where the productivity multiplier can be very high and I can do all sorts of things I never would've done. As I've mentioned in a number of my last posts, I have way too many of these projects to really be able to write them up, even when attempting to write very quickly and bash out posts in half an hour apiece. When I've talked to people about their one-off tooling, there's a lot of fun stuff people have done. For example, here's something Peter Geoghegan mentioned a month or two back: I had Fable implement a custom Neovim Lua function that formats code according to my very specific preferences. This is both something I don't want to maintain myself and inherently a Rube Goldberg device. Theoretically I could accomplish the same outcome in a principled way by patching clang-format, but my requirements are so exact that I think that approach would never be satisfactory. We use a tool call pgindent, which is our fork of bsd_indent. You can approximate the same formatting rules using clang-format, but that isn't good enough. If I commit something that isn't perfectly formatted/indented according to pgindent, I get a CI failure that I'm expected to fix quickly -- something I'd really prefer to avoid ... Practically speaking, getting slick, clang-format-style formatting that avoids nag emails about misindented code requires a total architectural mess (I also don't want to spend the time developing a principled approach, but that's really a separate issue). The function allows me to effortlessly format a given block of code from Neovim, similar to the clang-format LSP integration. I'm being unreasonably fussy here, of course, but I find that LLMs allow me to be this exacting about tooling. The function performs multiple passes: an initial formatting pass using clang-format/clangd, and a separate formatting pass using pgindent. I need it to do both because clang-format handles some cases correctly that pgindent misses. This is brittle because I only want to format the code within a range of lines selected via block visual mode (I don't want to run clang-format on code not added by my patch). This conflicts with pgindent's design; it can only format whole C files. Figuring out which relevant subset of the temp whole file buffer needs to be copied back into my working buffer is nontrivial. The initial line range I selected doesn't directly map to the affected C AST elements. So the function uses tree-sitter to intelligently delineate the exact subset of the temp indented C code that needs to be copied back. The rules need to be fuzzy in exactly the right way for cases where my selection straddles the same block of code. There are a bunch of edge cases. Another complicating factor is that pgindent relies on a typedef file generated with objdump to identify types; without that file, the formatting looks wonky. The formatting function dynamically generates any extra typedefs from clangd, for that one file, so I don't have to worry about a stale typedef file (I might have created a new struct seconds before running the formatting tool, I don't want to run objdump on the whole postgres binary each time, that'd blow up latency). This appears to work perfectly. The latency is totally acceptable. I have only a vague understanding of how all this works, though. I don't even know Lua. This will probably continue to work, even as further changes are made to our fork of bsd_indent that somewhat alter how code is formatted, which happens from time to time. I'm skeptical of the saaspocalypse. But I do think that LLMs are writing a lot of useful software that would have been insanely uneconomical to write any other way. There's an interesting small subset of software that'd be impossibly tedious for any human to maintain, relative to the value that it creates. I also caught with Malis while writing this and found out about all sorts of fun stuff he's been doing. It's enough that writing it all up in detail could be its own post, but one fun thing is that, the last time I taked to him about pgrust verification, he mentioned using Kani to verify some parts of the code. He's since switched to Lean and has been using Lean to verify things that are too complex to do in Kani. This would be another topic for another post, but I wonder why people have generally settled on Lean for LLM-driven proofs (as opposed to, say, ACL2 ). I wonder how Lean would look in an updated version of this theorem prover comparison , or if someone were to run a theorem prover eval that's analogous to this language eval . Of course, you can think of plenty of examples out of AI labs, such as a mid-sized team Anthropic building an internal replacement for GitHub as well as some other tooling in five months A team of seven people built both Scion and Antique (our code review tool, which we could easily write a whole other blog post about), not to mention half a dozen related systems, and fully migrated to them in five months. I think these kinds of examples are interesting and they point to where the industry will be in the not-so-far future, but what you can do with unlimited tokens, while relying on other infrastructure and tooling built with unlimited tokens doesn't tell you much about what you can accomplish today without unlimited funds. Projects like pgrust as well as projects that people I know do in their spare time (of which I've probably mentioned something like 1%—there are just a lot of these, like David Turner creating an skipper for podcasts that's "works for me" quality that works better than anything he could find, the spare-time projects Dennis Snell mentioned here , etc.) are more representative of what you can do today. One reason I trust Malis is that he's a lot more careful about what he claims than a stereotypical founder. For example, when I joined the pgrust discord to check out what people are saying, I saw this message from Malis (dated a month ago, 2026-09-17, an eternity in agentic coding land) in response someone asking about pgrust's readiness for use as a production database: I would not recommend using it as your primary production database today. We are setting a production deployment for a company right now, but they are more tolerant to their production database going down than most people. We'll have good empirical evidence on how reliable pgrust is after they start running it Malis doesn't seem like someone who would claim something is production ready when it's clearly wildly unready , like many well-known projects have, and it turns out he's not doing that. I wrote the draft of this a week before publishing and didn't have time to publish it. Since then, there was this pgrust Clickhouse benchmark controversy . On looking into this, the accusations of nefarious cheating seem to be false, and the accusation that it was premature to submit the preview of pgrust to the benchmark is something Malis acknowledged. I do think this is the kind of thing that a project will never live down, in that regardless of the truth of the matter, people will be bringing this up years later. You can see this right now in discussions around that specific controversy, and as we discussed when we look at Ed Zitron's prediction track record and when we looked at futurist predictors like Kurzwil , almost nobody actually looks at what actually happened and people will repeat incorrect statements that were based on vibes indefinitely. I don't think I can really present all of the evidence for why I trust Malis (technically, I could do it, but it would easily be a 20k+ word post), but if you look at how he discusses pgrust vs. how typical database founders market their new DB projects, it seems dramatically different to me. Of course there are extreme examples like MongoDB, which disputed correctness issues for years despite Kyle Kingsbury repeatedly showing that the anecdotes people had about data corruption were real. For an example that's more typical, a friend of mine worked as an early employee for a database startup. Their webpage bragged about doing some huge number of QPS. On testing it, my friend found that the claim was off by multiple orders of magnitude and suggested that the webpage get changed. The founder disagreed because they were going to hit the performance numbers, so it was still a true claim. After multiple years of performance improvements, the company eventually reduced the claim by one order of magnitude and they can still only hit that number with a very contrived, unrealistic, workload. This is, unfortunately, pretty normal for a company peddling a product based on its performance. By contrast, when I look at the pgrust discord to see what Malis is saying about performance, here's his most recent message: Right now, the best way to help is to find bugs and performance issues in 0.4-beta. The new query engine is very fast on some workloads, but it causes performance regressions on others, and it doesn't support some more complex queries. We're trying to track down everything that's either slower than Postgres or errors out. It's not an easy thing to do given the massive space of queries you can run We want to fix these things before the general release of 0.4-beta. Off the top of my head, there was a big performance regression in very fast queries. This is because we primarily optimized the new query engine for large-scale OLAP-like workloads. I'm doing optimization work to fix the very slow queries. I don't think there's any fundamental reason why the new engine should be slower than the previous one for fast queries Even though he was a founder and exec of a successful startup prior to starting the pgrust project, he never really got into the mindset that most founders seem to, where they seem to be able to say anything and believe anything they say. You might say this is a low bar, and I'd agree, but I still think it's rare and it's why I trusted what he says about pgrust without looking into it and also why, when I looked into it, his claims seem to be borne out by reality. Another way to look at it is [this framing from Thomas Ptacek]: The last year in the technology industry has felt like 100 years all happening at once. Our industry is destabilized in a way nobody’s experienced since the advent of the personal computer. Every limit AI runs up against collapses within a month. Everything we do with frontier models today, in a few years we’ll be doing instantaneously and for free. Given the pace of change recently, I find it understandable that most people, even most programmers, aren't quite aware of what's possible right now. Speaking to non-programmer responses, one of the things I thought was interesting was how many people objected to this review of Ed Zitron's prediction accuracy because they thought that AI capabilities hadn't increased in the past two years. For most people I talk to, the idea that AI didn't improve from fall 2024 to fall 2026 is completely baffling (even if you think of programming as an exception and look at other capabilities), but there's a lot of people out there who are perhaps looking at the Google AI summary at the top of search results or using Copilot integrated into some Microsoft suite, who don't realize that capabilities have advanced. At every scale, there seems to be an information gradient like this, where very few people outside of labs have a good idea of what the most productive people are doing with models today. This comment about an increase in cheating online has come to pass . On re-reading the actual comment that I wrote, I didn't explicitly write that it seemed inevitable that there would be a large increase in cheating, although it can be inferred from connecting the statements there together, and I've been on the record in public on some discords, etc. I don't follow the online game scene, but I'm told that for Azul (the most popular game on BGA, the biggest online board game platform for modern board games), 3 of the top 10 places last season were taken by cheaters, including top place. Also, as I've noted elsewhere in the past, BGA doesn't seem equipped to make reasonable policy decisions on almost any level. Things like the mechanics of their Elo ranking algorithm, their structure for game seasons, their policy for counteracting collusion, their policy for countering cheating, etc., are worse than the most naive straightforward solution you can think of so, as expected, they don't have a reasonable policy to counter cheating. The top ranks of the most popular game have been overrun with cheaters and this should be expected to spread to other games. As harms from AI go, this is a fairly benign one. It just happens to be one of a double-digit number of examples I saw last week of people being more ambitious in the software they create. I'm half mentioning this because it's easily quantifiable, and half because I predicted this would happen and it seems reasonable to follow up and see what happened. Compiling Rust Syscall and filesystem overhead In this post, we're going to use ambitious in a way that feels consistent to me, but that one could argue is overloaded. I'm using this to mean, doing more than you could've before, in a generic sense. One could say that there's a difference between building a project that's larger than was reasonably feasible before and building some kind of super-specialized tool that could've been done before but just wasn't worth the time to build. While these are very different things, I think they both fall out of the same thing (it being much easier to produce software), so I feel pretty comfortable with this arguably overloaded definition. [return] Alex Kolovsky pointed out that these were not considered a bug. I see the argument from a security standpoint and I don't have enough context on Postgres to weigh on on this specifically, but I'll say that, for projects I've worked on, I've liked eliminating this kind of issue because it's a lot easier to find real bugs if you try to make your code clean from all issues like this. [return] One reason I trust Malis is that he's a lot more careful about what he claims than a stereotypical founder. For example, when I joined the pgrust discord to check out what people are saying, I saw this message from Malis (dated a month ago, 2026-09-17, an eternity in agentic coding land) in response someone asking about pgrust's readiness for use as a production database: I would not recommend using it as your primary production database today. We are setting a production deployment for a company right now, but they are more tolerant to their production database going down than most people. We'll have good empirical evidence on how reliable pgrust is after they start running it Malis doesn't seem like someone who would claim something is production ready when it's clearly wildly unready , like many well-known projects have, and it turns out he's not doing that. I wrote the draft of this a week before publishing and didn't have time to publish it. Since then, there was this pgrust Clickhouse benchmark controversy . On looking into this, the accusations of nefarious cheating seem to be false, and the accusation that it was premature to submit the preview of pgrust to the benchmark is something Malis acknowledged. I do think this is the kind of thing that a project will never live down, in that regardless of the truth of the matter, people will be bringing this up years later. You can see this right now in discussions around that specific controversy, and as we discussed when we look at Ed Zitron's prediction track record and when we looked at futurist predictors like Kurzwil , almost nobody actually looks at what actually happened and people will repeat incorrect statements that were based on vibes indefinitely. I don't think I can really present all of the evidence for why I trust Malis (technically, I could do it, but it would easily be a 20k+ word post), but if you look at how he discusses pgrust vs. how typical database founders market their new DB projects, it seems dramatically different to me. Of course there are extreme examples like MongoDB, which disputed correctness issues for years despite Kyle Kingsbury repeatedly showing that the anecdotes people had about data corruption were real. For an example that's more typical, a friend of mine worked as an early employee for a database startup. Their webpage bragged about doing some huge number of QPS. On testing it, my friend found that the claim was off by multiple orders of magnitude and suggested that the webpage get changed. The founder disagreed because they were going to hit the performance numbers, so it was still a true claim. After multiple years of performance improvements, the company eventually reduced the claim by one order of magnitude and they can still only hit that number with a very contrived, unrealistic, workload. This is, unfortunately, pretty normal for a company peddling a product based on its performance. By contrast, when I look at the pgrust discord to see what Malis is saying about performance, here's his most recent message: Right now, the best way to help is to find bugs and performance issues in 0.4-beta. The new query engine is very fast on some workloads, but it causes performance regressions on others, and it doesn't support some more complex queries. We're trying to track down everything that's either slower than Postgres or errors out. It's not an easy thing to do given the massive space of queries you can run We want to fix these things before the general release of 0.4-beta. Off the top of my head, there was a big performance regression in very fast queries. This is because we primarily optimized the new query engine for large-scale OLAP-like workloads. I'm doing optimization work to fix the very slow queries. I don't think there's any fundamental reason why the new engine should be slower than the previous one for fast queries Even though he was a founder and exec of a successful startup prior to starting the pgrust project, he never really got into the mindset that most founders seem to, where they seem to be able to say anything and believe anything they say. You might say this is a low bar, and I'd agree, but I still think it's rare and it's why I trusted what he says about pgrust without looking into it and also why, when I looked into it, his claims seem to be borne out by reality. [return] Another way to look at it is [this framing from Thomas Ptacek]: The last year in the technology industry has felt like 100 years all happening at once. Our industry is destabilized in a way nobody’s experienced since the advent of the personal computer. Every limit AI runs up against collapses within a month. Everything we do with frontier models today, in a few years we’ll be doing instantaneously and for free. Given the pace of change recently, I find it understandable that most people, even most programmers, aren't quite aware of what's possible right now. Speaking to non-programmer responses, one of the things I thought was interesting was how many people objected to this review of Ed Zitron's prediction accuracy because they thought that AI capabilities hadn't increased in the past two years. For most people I talk to, the idea that AI didn't improve from fall 2024 to fall 2026 is completely baffling (even if you think of programming as an exception and look at other capabilities), but there's a lot of people out there who are perhaps looking at the Google AI summary at the top of search results or using Copilot integrated into some Microsoft suite, who don't realize that capabilities have advanced. At every scale, there seems to be an information gradient like this, where very few people outside of labs have a good idea of what the most productive people are doing with models today. [return] This comment about an increase in cheating online has come to pass . On re-reading the actual comment that I wrote, I didn't explicitly write that it seemed inevitable that there would be a large increase in cheating, although it can be inferred from connecting the statements there together, and I've been on the record in public on some discords, etc. I don't follow the online game scene, but I'm told that for Azul (the most popular game on BGA, the biggest online board game platform for modern board games), 3 of the top 10 places last season were taken by cheaters, including top place. Also, as I've noted elsewhere in the past, BGA doesn't seem equipped to make reasonable policy decisions on almost any level. Things like the mechanics of their Elo ranking algorithm, their structure for game seasons, their policy for counteracting collusion, their policy for countering cheating, etc., are worse than the most naive straightforward solution you can think of so, as expected, they don't have a reasonable policy to counter cheating. The top ranks of the most popular game have been overrun with cheaters and this should be expected to spread to other games. As harms from AI go, this is a fairly benign one. It just happens to be one of a double-digit number of examples I saw last week of people being more ambitious in the software they create. I'm half mentioning this because it's easily quantifiable, and half because I predicted this would happen and it seems reasonable to follow up and see what happened. [return] Pandoc supports {html, docx, xlsx, pptx, csv, markdown, gfm, commonmark, commonmark_x, markdown_strict, markdown_mmd, markdown_phpextra, markdown_github, rtf, epub, odt, tsv, latex, ipynb, mediawiki, rst, asciidoc, bibtex, biblatex, org, typst, jira, docbook, endnotexml, ris, opml, dokuwiki, textile, man, mdoc, jats, csljson, fb2, pod, vimwiki, djot, creole, tikiwiki, twiki, t2t, haddock, muse, json, xml, native} as input formats and {pdf, html, html4, docx, plain, pptx, markdown, gfm, commonmark, commonmark_x, markdown_strict, markdown_mmd, markdown_phpextra, markdown_github, rtf, epub, epub2, odt, latex, ipynb, mediawiki, rst, asciidoc, asciidoc_legacy, bibtex, biblatex, org, typst, bbcode, bbcode_phpbb, bbcode_steam, bbcode_xenforo, bbcode_fluxbb, bbcode_hubzilla, jira, docbook, docbook4, revealjs, beamer, opml, dokuwiki, textile, man, texinfo, context, jats, jats_publishing, jats_articleauthoring, tei, icml, opendocument, csljson, fb2, ansi, chunkedhtml, djot, xwiki, zimwiki, vimdoc, haddock, markua, muse, ms, slidy, s5, dzslides, slideous, json, xml, native} as output formats (native is a serialized version of Pandoc's AST). [return] BTW, this makes public evals not very meaningful for many use cases because what I and other programmers who are using models often care about is how good the model is at a task where the model still needs human guidance, not how good the model is at a task that's trivial for the model. [return] This is not a claim about the future. Perhaps almost all or perhaps even all of the software skills I have will become irrelevant in the near future. But we're not there yet. At the moment, programming skills seem higher leverage than ever before. There's something a bit funny about the current moment, where it seems like having the skills that models are replacing makes one much more effective than people who are trying to use models without having those skills. I like Max Bittker's framing that models are very good at counterfeiting and the level of expertise it takes to distinguish a counterfeit from the real thing has been increasing as models improve. [return]

0 views
Sean Goedecke 1 months ago

Software is slow because of bad design, not slow languages

Many people are saying that AI will make software faster by rewriting it in faster languages, but this isn’t generally true. Most programs cannot be meaningfully sped up by rewriting them in C or Rust. How can this be true? Some languages are orders-of-magnitude faster than others: for instance, C can be fifty times faster than Python. Won’t rewriting my Python program in C thus make it fifty times faster? No, it won’t. Software performance is usually dominated by I/O, not the speed of the language. Where language speed matters, most slow languages already have popular libraries that allow them to unlock C-like speed. In general, performance is a matter of design , not of language choice. Consider a simple CRUD website with a database. For any given request, 50% of the request time 1 might be spent querying the database: to fetch the current user, the record being asked for, any relevant user memberships or settings, and so on. Rewriting that website in C can only speed up that other 50%, which puts a hard ceiling on the improvements you can make 2 . At best, you’ll make requests twice as fast (probably closer to 1.5x in practice). That’s not bad, but it’s nowhere near an order-of-magnitude speedup. In other words, most real programs are “I/O-bound”: they spend most of their time waiting for data to be input or output somewhere, as opposed to “CPU-bound” programs that spend most of their time actively doing things. I/O-bound programs don’t just have to rely on a database. Often programs have to wait on some third-party API, or on writing or reading data to disk. You could speed the code in up by 100x and you probably wouldn’t even notice, because spends all of its time waiting on the network. What about work that is obviously not I/O-bound? For instance, wikis have to turn stored markdown into renderable HTML 3 . Wouldn’t rewriting that in a faster language cause a massive speedup? It would! That’s why applications that do that use libraries like cmark-gfm that call out to fast languages for markdown rendering. In general, most slow languages can write very fast programs by invoking this kind of library. Python is famously a slow language, but it’s a competitive choice for CPU-bound workloads like machine learning and mathematics, because it has a healthy set of libraries that let it offload these workloads to fast C code. If a Python program spends 80% of its time doing matrix multiplications on a GPU, you are very unlikely to be able to speed it up by rewriting it in C, because those matrix multiplications are already happening in tightly-optimized C or assembly code. Of course, some programs do in fact do a lot of CPU-bound work in slow languages. If a program has not had much engineering attention, there will probably be a lot of low-hanging fruit . But these programs are often unimportant: if they were important, someone would have gone in and optimized them already, before AI made it (relatively) easy. That doesn’t mean it’s impossible to find a useful program to rewrite. Actual Computer recently rewrote tiktoken in assembly, providing a significant 4 speedup. However, you’re not going to revolutionize some field of computing like this. Even fast tokenization is only useful on the margins, because time spent in tokenization is a fraction of the time spent in inference. Despite all this, I think most software is far slower than it could be. I’m optimistic about the potential (with or without AI) to significantly speed up commonly-used software. But I think most of these speedups will come from redesigning the program, not rewriting it in a faster language. In a 2018 post , Bryan Cantrill described trying to rewrite a C program into Rust. It was difficult because the carefully-optimized design of the C program did not play well with the Rust borrow checker. Giving up, he simply wrote the program in Rust in the naive way, expecting a 20% slowdown or worse. Instead, it was 30% faster . The reasons boil down to Rust’s internal preference for a B-tree over a binary search tree, which happens to be a more cache-efficient data structure. So even in a largely CPU-bound workload, in the hands of someone very skilled at writing fast C, performance is dominated by design, not by language speed. This matches my own experience in higher-level languages. When I think of the significant speedups I’ve managed, they’re almost exclusively redesigns of the software to do less work: All of these strategies are completely unrelated to how fast the language is. In fact, writing in a slow higher-level language can make it much easier to optimize the code, because you can see at a glance what the program is doing. If (for some reason) I had first rewritten the web server in assembly, I would have a much harder time noticing the N+1 query, or the fact that we could move an API call into a job, and so on. Right now everyone is asking their AI agents to rewrite programs in Rust or C or assembly. This is fun, but it’s not a serious attempt at optimization. The set of programs that can be meaningfully sped up by this kind of rewrite is very narrow. If you want to make everything faster with AI — and you should! — you ought instead to be asking your agent to profile programs, identify hotspots, and suggest ways to redesign what the program does. Occasionally you may run into a hotspot that is truly CPU-bound and cannot be refactored to do less work. In these rare cases, rewriting that section in a faster language will help. But simply rewriting from the start will be far less successful than most people imagine. There are many good reasons to rewrite software in a different language: portability, efficiency, maintainability, and so on. But in terms of raw speed , you’re better off focusing on the program’s design. This might seem ridiculously high (if you typically work with slow languages or CPU-bound workloads), or ridiculously low (if you don’t). In my experience it’s at least in the ballpark for interpreted languages. This is formally called Amdahl’s law . Why not just store the HTML? You can, but sometimes the content of the HTML differs per-user (and even if you store the HTML you have to convert it at least once). They claim 4-23x faster than tiktoken and it was indeed ~5x faster on my laptop — though arguably this speedup comes from a redesign to avoid the dependency on regex, not on any intrinsic slowness of Rust with Python bindings. Caching a slow operation (typically an external API call) Performing slow operations asynchronously, either in a background job or out of the request/response lifecycle Performing operations in parallel instead of sequentially (sometimes breaking up large operations in order to do this) Replacing a set of SQL queries with a single SQL query (fixing N+1 problems) Replacing a slow SQL query with a fast SQL query Skipping unnecessary slow operations (e.g. in a paginated view, only fetch ancillary data from entities that are on the current page) This might seem ridiculously high (if you typically work with slow languages or CPU-bound workloads), or ridiculously low (if you don’t). In my experience it’s at least in the ballpark for interpreted languages. ↩ This is formally called Amdahl’s law . ↩ Why not just store the HTML? You can, but sometimes the content of the HTML differs per-user (and even if you store the HTML you have to convert it at least once). ↩ They claim 4-23x faster than tiktoken and it was indeed ~5x faster on my laptop — though arguably this speedup comes from a redesign to avoid the dependency on regex, not on any intrinsic slowness of Rust with Python bindings. ↩

0 views
Xe Iaso 1 months ago

Jesus Christ patch your shit now

In the hours following the release of CVE-2026-109618 for the project PHP , site reliability workers and systems administrators scrambled to desperately rebuild and patch all their systems to fix multiple memory safety vulnerabilities that allow attackers to execute arbitrary code on your server. This isn't something you can just mitigate and be fine. You MUST patch this. Don't try to bargain here. This is due to the affected components being written in C, the only programming language where these vulnerabilities regularly happen. "This was a terrible tragedy, but sometimes these things just happen and there's nothing anyone can do to stop them," said programmer Lady Miracle Kreiger, echoing statements expressed by hundreds of thousands of programmers who use the only language where 90% of the world's memory safety vulnerabilities have occurred in the last 50 years, and whose projects are 20 times more likely to have security vulnerabilities. "It's a shame, but what can we do? There really isn't anything we can do to prevent memory safety vulnerabilities from happening if the programmer doesn't want to write their code in a robust manner." At press time, users of the only programming language in the world where these vulnerabilities regularly happen once or twice per quarter for the last eight years were referring to themselves and their situation as "helpless."

0 views
Xe Iaso 1 months ago

"No way to prevent this" say users of only language where this regularly happens

In the hours following the release of CVE-2026-107891 for the project musl , site reliability workers and systems administrators scrambled to desperately rebuild and patch all their systems to fix multiple integer overflows in regcomp() when compiling untrusted regular expressions, leading to undersized allocations and possible out-of-bounds heap writes, denial of service, and arbitrary code execution. This is due to the affected components being written in C, the only programming language where these vulnerabilities regularly happen. "This was a terrible tragedy, but sometimes these things just happen and there's nothing anyone can do to stop them," said programmer Dr. Otho Conroy, echoing statements expressed by hundreds of thousands of programmers who use the only language where 90% of the world's memory safety vulnerabilities have occurred in the last 50 years, and whose projects are 20 times more likely to have security vulnerabilities. "It's a shame, but what can we do? There really isn't anything we can do to prevent memory safety vulnerabilities from happening if the programmer doesn't want to write their code in a robust manner." At press time, users of the only programming language in the world where these vulnerabilities regularly happen once or twice per quarter for the last eight years were referring to themselves and their situation as "helpless."

0 views
Xe Iaso 1 months ago

"No way to prevent this" say users of only language where this regularly happens

In the hours following the release of CVE-2026-111497 for the project Brotli , site reliability workers and systems administrators scrambled to desperately rebuild and patch all their systems to fix an out-of-bounds write in the Brotli decoder that permits remote code execution when processing malformed compressed streams. This is due to the affected components being written in C, the only programming language where these vulnerabilities regularly happen. "This was a terrible tragedy, but sometimes these things just happen and there's nothing anyone can do to stop them," said programmer Dr. Lester Cremin, echoing statements expressed by hundreds of thousands of programmers who use the only language where 90% of the world's memory safety vulnerabilities have occurred in the last 50 years, and whose projects are 20 times more likely to have security vulnerabilities. "It's a shame, but what can we do? There really isn't anything we can do to prevent memory safety vulnerabilities from happening if the programmer doesn't want to write their code in a robust manner." At press time, users of the only programming language in the world where these vulnerabilities regularly happen once or twice per quarter for the last eight years were referring to themselves and their situation as "helpless."

0 views
Xe Iaso 1 months ago

"No way to prevent this" say users of only language where this regularly happens

In the hours following the release of CVE-2026-111813 for Apache Traffic Server , site reliability workers and systems administrators scrambled to patch systems running its experimental magick plugin. In its default unsigned configuration, the plugin lets unauthenticated clients control arguments passed to ImageMagick convert, allowing anyone to execute whatever command they want on the server. The affected plugin is written in C++, whose users were relieved that this time the attacker did not even have to corrupt memory to tell the server what to do. "This was a terrible tragedy, but sometimes these things just happen and there's nothing anyone can do to stop them," said programmer Mr. Friedrich Frami, whose image processing plugin accepted instructions from anyone who could construct a URL. "It's a shame, but what can we do? There really isn't any way to know whether a stranger on the internet should be allowed to choose command arguments for a program running on our server. We made signature verification optional, so we've already done everything we can." At press time, administrators installing versions 9.2.16, 10.1.5, or 10.2.1 to fix the issue were referring to themselves and their situation as "helpless."

0 views
Xe Iaso 1 months ago

"No way to prevent this" say users of only language where this regularly happens

In the hours following the release of CVE-2026-94300 for the project BIND 9 named , site reliability workers and systems administrators scrambled to desperately rebuild and patch all their systems to fix memory corruption in named triggered by replaying captured GSS-TSIG-signed UDP messages while the negotiated TSIG key remains valid, potentially allowing remote code execution when combined with crafted queries to an attacker-controlled zone. This is due to the affected components being written in C, the only programming language where these vulnerabilities regularly happen. "This was a terrible tragedy, but sometimes these things just happen and there's nothing anyone can do to stop them," said programmer Queen Aniya Rippin, echoing statements expressed by hundreds of thousands of programmers who use the only language where 90% of the world's memory safety vulnerabilities have occurred in the last 50 years, and whose projects are 20 times more likely to have security vulnerabilities. "It's a shame, but what can we do? There really isn't anything we can do to prevent memory safety vulnerabilities from happening if the programmer doesn't want to write their code in a robust manner." At press time, users of the only programming language in the world where these vulnerabilities regularly happen once or twice per quarter for the last eight years were referring to themselves and their situation as "helpless."

0 views

How I am reading more

We live in what is being referred to as a “ post literate society ” in which 40% of Americans did not read a single book last year . This is mind blowing to me, but - I can also see that with screentime (on a phone alone) being somewhere over 5 hours a day , it makes sense where most of everyone’s time is going. However, if we can replace even one of those hours of that screentime with reading books, and that will amount to reading far more than 0 books per year! I generally read around 20 books per year, but I figured that I could do far better than that (and did in 2023 ). That year also coincided with massive personal, spiritual, and professional growth - I don’t think that this is mutually exclusive and is probably correlative. This year, I made a resolution to get back at it, and this is how I am reading more. The most important thing I think nearly anyone can do to read more is reduce screentime on a phone. By simply installing Kindle, KoReader, Libby, AudioBookshelf, MuPDF, or one of many other reading apps, we can use this in lieu of doomscrolling social media and news websites. Going further, we can delete social applications, youtube, and even the browser, and replace any idle time at checkouts, commuting, and where you would historically be “wasting time” with reading and listening to books. We are simply going to “waste time”… better! While I personally don’t subscribe to this method in that I don’t retain nearly as much that is being said in audio form (this is why I don’t consume podcasts, either), some swear by the ability to read while on the go simply by listening to books. If it works for you, then awesome! I just don’t seem to benefit much from audiobooks. I may revisit this though for driving and the gym and update this post if I do use audio more often. My wife hates this one trick! This, for me, has been the biggest eye opener and allowed me to read ~100 pages per day over the past month or so of this experiment. I simply have books lying around in my office, in the living room, my Kobo sitting next to the bed, etc. and instead of picking up my phone, I pickup a book instead. All things are downstream of how we spend our time - time spent reading begets more reading. Some may not like this in that they want to read one book to completion before starting on the next. I personally have anywhere from 5-15 books on the go at once. Off the top of my head, here is a non-exhaustive list of what I have on the go: I find that reading this way is tremendously interesting in that there is “cross-pollination” between domains and a growing connection between all things. You will find authors across time and geographical location discussing the same quote, book, or idea, across domains of theology, physics, computer science, design, art, everything. I then sit and meditate with what I’ve ingested, and create connections of my own. It’s fascinating. Not only this but, it’s a “cheat” in that if I get bored with one book/topic, I just go on to another, in one big circle. Boredom doesn’t mean ceasing to read, just selecting something else that I am actually in the mood for. The very first thing I do in the morning is make the Sign of the Cross and Pray. The very next thing I do is sit down to read. I have started to wake up earlier in order to get the time to myself so I can do this, and it is truly awesome to get an hour or so or reading in before starting work. I read 10 pages, do some pushups and stretching, read 10 more pages, more physical activity, and repeat for about an hour. Most days I get about 30-50 pages in before anything, and I feel that it gets the wheels turning in my mind for writing, creating, etc. as I have always found reading to be “conversational”. I am not usually gung-ho in the morning to immediately begin working, and this has immensely helped my ability to drop into work and the rest of the day. Try it out! If you are so inclined to use applications such as Goodreads or the like, then this can be a fun way to keep track of that which you are reading and “compete” with friends. I’d recommend against giving Amazon all your data, but you do you. I also think that reading has become an extension of social media in that there is an element of “one-uppmanship” which I don’t care to participate in. I personally keep a /reading page on my blog for the current year, and keep track that way. It’s a fun way to discuss books when people can see what you’re reading on your blog and it’s a good conversation starter. I have always hated the rationalization that “reading is too slow”, or that “I have no time to read!” As I said above, if you have time to scroll your phone, you have time to read and converse with the greatest minds that have ever lived. We need to slow down more than ever in this crazy, accelerating world. I find that almost no one sits and chews on ideas anymore, and that is detrimental to the future of humanity if we are not to create polymaths and people of skill. If we don’t have time to read, we don’t have time to grow, and that is simply not true. So, read more! I am thankful that my parents and teachers instilled a love of reading in me from a young age. Truly, one can learn about anything and everything if we only pick up a book and start flipping through. I personally don’t want to live in a post-literate society, I want to discuss these great works and continue to learn from everyone that’s come before, so that is why I choose to keep reading, and to read as much as I possibly can. Try it out for a month, and see how much you fall (back) in love with reading. I think we have all just forgotten how amazing it is to pick up a great book and lose ourselves in the worlds and ideas of another’s mind. As always, God bless, and until next time. If you enjoyed this post, consider Supporting my work , Checking out my book , Working with me , or sending me an Email to tell me what you think. The Brothers Karamazov The Go Programming Language The Art of Unix Programming The Republic An Introduction to the Devout Life The C Programming Language (K&R) Structure and Interpretation of Computer Programs Chruch Fathers Against the Machine The Bible (Everyday, first thing I read) Operating Systems, Three Easy Pieces Computer Systems: A Programmers Perspective Designing Data-Intensive Applications

0 views
daniel.haxx.se 1 months ago

A UAF turned RCE

In the curl 8.23.0 release we shipped a fix for one of the worst vulnerabilities in curl in a long time. We grade it severity HIGH. It is known as CVE-2026-92392 with the title HTTP/2 upload Use-After-Free . This post explains the bug, what the problem can lead to, and something about why it happened and what we have done to make it harder to introduce a problem like this in curl again in the future. This is a much simplified explanation. Please refer to the original report for all the details and the full reproducible Docker image for all the low-level fun and education you could possibly want. I highly recommend doing that; the report and the reproducible are awesome. It is a use-after-free , which is a classic problem in memory-unsafe programming languages, like C, where we erroneously have a lingering pointer left, pointing to memory that is already freed, and yet we use that pointer and the memory it points to. This family of errors is especially bad when a malicious actor can affect the content that gets stored into that memory area that is still used even though it was freed. Tricking the program to do something unintended. This problem involves HTTP/2. HTTP/2 is a multiplexed protocol, meaning that it handles multiple logical transfers over the same physical connection. curl needs to keep track of a number of transfers at the same time, and when data arrives or is to be sent off, it needs to keep things apart appropriately. For every transfer done using libcurl, the application creates and sets up a dedicated handle . We call it an easy handle . This handle is kept around for as long as the transfer is in progress, and the application can close and free it once the operation is completed. When doing multiple transfers, multiple handles are used. libcurl also has multi handles , which is a super handle type that holds any amount of easy handles . This handle, and the corresponding multi interface, makes it possible to drive any amount of concurrent transfers. A transfer done with libcurl always has at least one multi handle and one easy handle. (Sometimes the multi handle is hiddenly used under the hood.) In order to trigger this problem, we need an application (such as the curl command line tool) to do an upload over HTTP/2 to a server. By default, libcurl negotiates HTTP/2 when a HTTPS:// URLs is used and the server agrees. When the upload has started, the server pauses the send by zeroing the HTTP/2 window size, returns a piece of the response and then it resets the stream, which shuts down the transfer – but not the connection. curl then correctly pulls down the entire transfer, but it accidentally leaves a lingering pointer to the involved easy handle . When the application finds out that the transfer completed (with an error), it subsequently frees the easy handle and then, and here comes the problematic part: cleans up the multi handle. At this point, the easy handle was just freed but there is still a reference to that handle. When libcurl shuts down the multi handle, it misunderstands the situation, allocates memory to download data into, finds the still dangling pointer and manages to download data from the server that ends up in the very same memory previously used for the easy handle. In this process, it sends off a request that leaks internal client details, which includes information about local addresses, which is crucial. Modern operating systems use Address Space Layout Randomization (ASLR), so a server needs this clue in order to generate a good attack payload. Subsequently, when libcurl deals with this received data (using the handle the dangling pointer points to) in the download buffer, it uses a function pointer that now has been modified by data just downloaded from the server, and then it runs remote code . Here’s a simplified 6-step illustration. Conditions to trigger In order to actually successfully execute remote code, lots of several specific conditions need to be met and we deem it extremely difficult to meet these requirements in the wild, which is why we decided this is “only” severity HIGH and not CRITICAL. The most likely outcome of an attempted attack is rather just a crash. We estimate that the chance for a successful attack is slim. This problem was found and reported by Luna Tong at Anthropic using their new OSS Scanner. Presumably this involves their AI models. In general we have over the last few years been working on reducing the amount of internal pointers to handles that needs to be correct, and instead we store transfer identifiers that we look-up on demand. While this is a tiny bit slower, it is more foolproof when there are logical mistakes like the one mentioned here. We also of course continue to add more tests and we verify the code with more tools and analyzers in order to find additional similar mistakes. Multiplexed protocols like HTTP/2 have this challenge that there are many concurrent transfers going and they all have different life-times and with memory-unsafe languages, dangling pointer mistakes can indeed be fatal. This is of course no guarantee that we do not have or will not introduce another use-after-free in the code now or later. libcurl is written in C – a memory unsafe language. With a memory-safe language, this mistake could probably have been avoided. We have worked on curl for almost thirty years, and have over this time manage to make a rather polished transfer engine. For the longest time there really was no memory-safe alternative that also allowed libcurl to be a low-level library available on hundreds of operating systems and several dozen CPU architectures. It even barely exist alternatives now. We do not rewrite curl. Not into another language but also not in C. We are set to iterate, polish, improve, refactor over and over until the end of time. Porting curl to another language (like rust) would be a monstrous undertaking that would be slow and introduce lots of new short to medium term problems. Not to mention that the existing curl team is not rust experts and that libcurl is currently portable to many more platforms and environments than rust itself is. When this vulnerability was confirmed by the curl security team just hours after it was submitted to us on September 15. We immediately realized the significance and decided to rush the pending next release. However, we still wanted to be careful, follow the procedures and not create any further problems or mistakes by stressing it too much. That’s how we ended up just shortening the release cycle with two weeks. Down from eight to six weeks from the previous release. This allowed us to also merge and fix many more vulnerabilities and general bugs in the same release. We never provide CVSS for our published vulnerabilities as we don’t think we can do a job there. Others will provide them even for our flaws. The victim needs to actually attempt to upload data to a malicious server, meaning that the server certificate must remain valid. The size of the upload needs to be roughly the right size (~135KB) The attacker needs to know curl’s architecture to generate and deliver the right code The attack requires a specific sequence of allocations and allocation sizes so that the data from the server ends up in the right place (from the attacker’s view). This pattern differs between Linux distros, libc versions/flavors, TLS certificate bundles, libcurl using applications and more. nghttp2 and OpenSSL/TLS 1.3 behavior, including allocation effects around session tickets The payload storage area is small (around 23 bytes)

0 views
Michael Lynch 1 months ago

Why Are Coding Agents So Dumb?

The first time I used a coding agent, I was mesmerized . Before the agent, I was copy/pasting between my IDE and an AI chat interface. It was amazing to see an agent edit files directly and fix its own errors in real time. After a few days, the honeymoon wore off as I encountered frequent bugs. The agent would stop responding entirely until I restarted it. Development workflows felt stiflingly primitive, and the agent would often declare tasks finished when work had barely begun. This was in February 2025, so it was still early days for coding agents. I figured that in six months, agents would be as technically impressive as the underlying LLMs. Instead, coding agents just stayed bad. AI-assisted development has clearly advanced, but the models are doing the heavy lifting while the agents remain the bottleneck. In all the hype around AI, the terms tend to get distorted. People are beginning to overload and mix terms like “model” and “agent.” When I say “model,” I’m talking about large language models (LLMs) like GPT Astra, Claude Sonnet, and GLM-5.3. Models generate text and images, including pretty good software code. When I say “agent,” I mean the software that connects models to codebases and computer systems. These are tools like Anthropic’s Claude Code or OpenAI’s Codex. As a simple analogy, the model is the brain, and the agent is the body. The model produces a stream of text, and the agent acts as the glue that plugs the text into the right commands and files on the system. My biggest gripe with coding agents is how atrociously they manage tasks. For example, I have an open-source web app that generates shareable links for file uploads. I recently added support for protecting links with a passphrase . It was a relatively simple change, totalling about 1.5k lines of new code. OpenCode dutifully broke the feature into 10 subtasks, but then it just… did them all one by one: Why are you doing these embarrassingly parallel tasks one at a time? Umm… you’re a computer ! You’re really good at multitasking. That’s why we keep giving you all those CPU cores. You can do multiple things in parallel and context switch millions of times faster than humans. Why are you doing these embarrassingly parallel tasks one at a time? Claude Code multitasks, but only a little. It will spin up a subagent or two, but it still waits for all of them to finish before moving on. Multiple times per day, I’ll see Claude Code sit around for several minutes waiting for my end-to-end tests to finish, and then only after the tests pass does it say, “Hmm, now I should start drafting a commit message. Let me look at the git history to learn your commit message conventions .” When I’m using a cutting-edge model, and it needs to check 50k lines of code for a particular pattern, the agent never stops and says, “Wait, this is something another model could do cheaper and faster.” It just plows on with the slow, expensive model. Conversely, the agent never says, “This model is too dumb for this task. Let me tag in a smarter one.” Of course, I can actively micromanage the task and keep switching the model and thinking level to match each subtask’s difficulty, but why is that my job? Do you also need me to manage your thread pool for you? Do you expect me free your unused RAM for you, too? You know what technology would be good at assigning a difficulty level to a task and then matching those requirements to a model? An LLM! Just ask the LLM to pick the cheapest, fastest model for the task. Why do you need me to babysit you? I constantly run into tasks that are 95% gruntwork, but I still have to assign them to the smartest model because chopping up the task and delegating on the agent’s behalf would take up too much of my time. Thanks for telling me which is the default model, Claude. Agents don’t know anything about themselves. If I ask Claude how to use the features of Claude, it has to search online to figure out what this “Claude” thing is. Claude is more comfortable answering questions about C programming than talking about itself (in fairness, same with most human developers). Uh… you’re Claude Code! You don’t know any of your own freaking features? And you’re just Googling instructions regardless of whether they match your version number? You’ll casually download 13 GB of files for a feature the user has never used, but you can’t spare 50 KB of gzipped text in your install package to explain your own features to you? Imagine if you asked your teammate for a code review , and they started furiously Googling to find out if code reviews are something developers do. And then when you asked them for another code review the next day, they had no memory of your previous conversation and ran back to Google and anxiously typed, I used to love the agent UX feature of separate “Plan” and “Execute” modes. For complicated tasks, I’d ask the agent to create a plan, then I’d review it, suggest changes, and delegate execution to a faster, cheaper agent. Over time, I felt an aversion to reading the plans. I’d often skip my review and just let the agent move straight to implementation. I thought coding agents had made me lazy, but I realized that agents just communicate their plans so poorly that they’re painful to read. Here’s an example of me asking Codex + GPT-6 Astra to add a feature to my media journalling web app : You can’t just list a bunch of disparate details and call it a plan, Codex. That’s not a plan! That’s just a hodgepodge of low-level design decisions. If I asked a competent developer to plan this feature, they’d either start with a high-level plan for UI changes and work their way down or describe changes to the data model and work their way up. If the developer started enumerating random facts about the feature, I’d assume they were brainstorming and come back later. The other night, I kicked off a long task in a coding agent before I went to bed. I came back the next morning to find that the agent hadn’t even started working. It stopped two minutes after I left to ask me what it should name a git branch and then sat all night waiting for my answer. If I had a human employee tell me they sat idle their whole shift because they wanted my input on some superficial detail, I’d quickly fire them. When I started using my first coding agent, I looked for the setting that controlled which files on my system the agent is allowed to access. Surely, there was some sort of filesystem permissions or limited chroot kind of protection that prevents a random and unpredictable piece of software from exploring my entire computer unfettered, right? Not so. The docs encouraged me to write the LLM a polite letter kindly requesting that it not read certain files or directories. I tried that, and the agent immediately ignored my request, exfiltrating private application keys to OpenAI and Anthropic. I thought that security boundaries would be one of the first things coding agents would implement, but even today, agents are only usable if you give them access to everything. Agents routinely bypass their own vendors’ sandboxes . The alternative is to sit there and click “Allow” 500 times a day, and that’s not even reliable protection because you’re bound to misclick eventually. What makes this so maddening is that we’ve had sandboxing tools for more than a decade that can limit the blast radius of mistakes from coding agents. I rolled my own sandbox so that agents can’t explore my filesystem beyond the repo directory. I never have to worry about agents accidentally exfiltrating my home directory or wiping critical files on my machine because they just don’t have access to do that. I know some readers will say that I can solve all of my problems if I just install 200k lines of skill files from random git repos or set some obscure feature flag in my config file. I’m talking about my expectations of what coding agents should be able to do out of the box without me installing random plugins or skill files or spending hours tweaking the configuration. These are the basics that I think should be table stakes for coding agents in 2026. As long as I’m dreaming, here are some additional features I’d like to see, but I recognize that some of these are overindexing on my personal workflows. Okay, getting back to the question in the title, I don’t have a satisfying answer. My best hypothesis is that underinvestment in coding agents is an example of the principal-agent problem . The people setting the direction of AI tooling are executives at companies like Anthropic, OpenAI, and Google. Those executives are disconnected from the rank-and-file developers who use coding agents every day. Many of these executives are dreaming of a future where they can automate away human developers entirely. AI executives, as well as their largest customers and shareholders, pay attention to metrics that are legible to them, such as slick demos and benchmark scores. Security and efficient use of human developer time aren’t relevant to the demos, and barely any of the benchmarks I’ve seen measure the agents themselves; they just measure the underlying models. My hypothesis isn’t satisfying because AI companies clearly care at least a little bit about coding agents. I see a lot of features being added to Claude and Codex every month, though I can’t recall the last time one of them has improved my life. I’ve only tried Claude, Codex, OpenCode, Cline, and Pi. I use OpenCode and Claude Code as my daily drivers. If you’ve got a coding agent recommendation for me, comment below. AI companies - if you want to acquire my imaginary coding agent for $50B, let me know. I’m ready to fork VS Code at a moment’s notice. The agent splits requests into a series of tasks and assigns each task to the appropriate model. The agent optimizes for cost, speed, and correctness and allows the user to adjust the dials per task (e.g., spend more for a faster result). The agent writes plans that optimize for human comprehension. The agent starts at a high level of abstraction and progresses toward the minutiae . The agent creates UI mockups, data flow diagrams, and decision trees . The agent operates within a real sandbox. The sandbox uses OS-level security primitives to create boundaries at the filesystem and networking level. All access control code is deterministic, not humble suggestions that the agent is welcome to ignore. If I ask the agent whether a list of regexes on bash commands is a sandbox, it replies, “No.” The agent applies per-environment sandboxing. The agent has access to a single repo/directory by default. I can give the agent read-only or read-write access to other repos on a per-session basis. The agent is an expert on itself. If I ask the agent how to express a task or workflow to the agent, it knows the answer without having to search online. The agent can use any LLM provider, including unlimited plans. The agent is open-source. If I don’t answer a question in “Execute” mode, and I haven’t interacted with the session in 30 minutes, the agent makes the decision independently. The agent also offers an “AFK mode,” which skips the 30-minute wait. The agent lets me drive the subagents, too. I should be able to jump into any agent session and drive it or tell it to short-circuit and end early. If the agent tells me that Fable is not available on my Max plan , the agent vendor’s CEO must remain in stockades until the bug is fixed. The agent offers a web interface that shows me a unified view of all sessions and which ones require attention. The web backend runs locally and doesn’t require me to open a tunnel from the Internet that executes arbitrary commands on my system. The web interface works well on my phone. The agent maintains an ETA for task completion. Each subagent maintains its own ETA as well. The agent continuously updates this estimate as the task progresses. The agent tunes its estimation algorithm based on the accuracy of its past estimates. The agent reviews its own sessions and looks for opportunities to improve. e.g., “Wow, I blew through $1k/day in tokens the past five days trying to parse this 20 GB log file with ad-hoc commands. Let’s build a custom tool to do this efficiently.” The agent comes with a good language-aware diff view. I don’t want to have to push to GitHub to see a useful diff of the agent’s work. The agent natively supports a proxy for injecting secrets into network requests. The agent can make requests that require credentials but can’t exfiltrate the credentials to another host. The agent considers provider quota limits when selecting an appropriate model. e.g., if my weekly quota resets in 3 hours, and we still have 90% of quota available, stop optimizing for cost. For tasks above a configurable complexity threshold, the agent automatically requests a code review from another model. The two models iterate on reviews until they converge on the fixes.

0 views
pkh.me 1 months ago

Float and integer arithmetic follow two different paradigms

When working with floats, we tend to reuse the more familiar integer arithmetic patterns. More specifically, we always try to prevent a disaster rather than reacting to it. I keep noticing this pattern over and over again, and seeing that LLMs still get it wrong most of the time means that, either I am wrong, or everyone else is; it's obviously the latter, and I'm going to explain why. I wrote before about the issue with checking the result of integer arithmetic after the catastrophe happened . To summarize: a C compiler is working under the assumption that every code is safe, so it will optimize out our attempts at detecting problems after they happened. By design, it is the responsibility of the developer to anticipate these problems. This is not exactly specific to C, for example in Rust we still need to prepare for an operation to fail by using the corresponding checked/wrapping/saturating/overflowing operator functions ( , , etc). Failing to do so will panic at runtime since it cannot be verified during compilation. In C we need to do this manually through different degrees of gymnastics, typically through smart computations involving constants like , or using the compiler builtins such as (C23 also finally standardized with function helpers). Not being diligent about these issues ultimately leads to undefined behavior (or a forced crash with compiler options such as ) and security issues, which means developers have been more careful over time, or at least familiar with the possible shortcomings. IEEE-754 floating-point types are an entirely different beast and need a new paradigm. Operation errors create (not a number) or infinite values, which propagates through calculations. They do not crash the program, and they're perfectly legitimate. Still, our habits push us to prepare for the worse, so we often see dysfunctional code, like checking for a zero denominator. Here is an example with ChatGPT (October 2026): When people realize operations with tiny floats can also cause infinite, they start using an arbitrary small epsilon ε, adjusting the check with something like . Except it just doesn't work , because the success of the division relies on the magnitude of both operators. For example, the largest 32-bit float (somewhere around 3.4 \times 10^{38} ) divided by a number below 1 (for example y=0.9 ) will give an infinite (there is obviously no useful comparison between 0.9 and possible here). Similarly, if x=5 \times 10^{31} , and we divide it by the next representable float above , we also get an infinite. We can verify that with the following rust snippet: Looking for , , or equivalent in a random codebase will, in most cases, raise broken checks. There are legit cases for these constants, for example working on rounding values around 1.0, but most often they're abused for error handling in suspicious ways. So what are we supposed to do? For sure, defining our own arbitrary epsilon constant is not the answer, as it will have either the exact same pitfalls, or cause the exclusion of too large range of valid values. Well, the answer is simple. We simply have to check if the result of our calculations is a finite number: in Rust, in C, etc. If we don't get a number, or get an infinite, we're just in a degenerate case: The article assumes IEEE-754 implementation in our C environment, let's try to stay sane here. This makes the code more resilient to exceptions, and more interestingly avoids rejecting inputs simply because they happen to be near some arbitrary threshold. It works particularly well with more complex formulas and algorithms, because unexpected faults such as a negative square root, or 0/0, will have a traveling safely through the end result. Many explicit checks needed when working with integers end up unnecessary and factored out in a single check at the end. Infinite, typically caused by overflows, while not being as contagious as , also propagate through the arithmetic operations in reasonable ways. For example, 1/\infty=0 is expected. Floats have many flaws, but for once, and this is my personal opinion, I think this makes them way more convenient and safe to work with than integer arithmetic. Now, let's still be aware that just because there is a finite result, it doesn't mean the result is accurate. won't magically protect from numerical instability, which can produce some beautifully refined finite garbage: In the most float centric development environment, the graphics stack, might not be available, unless we use precision (conditioned by ). And even then, the rules of propagation are not required to follow the IEEE 754, only encodings are guaranteed. Operations (add and mult) do not necessarily comply. As a direct consequence, GLSL doesn't provide , but rather has the opposite , which doesn't cover the case (we're expected to use + , keeping in mind is not expected to work reliably). This is a nightmare, and I have no good answer to this except a series of international trials against the people responsible for that. In the meantime, there is a proposed implementation in my previous article on cubic bézier , but it will still not work if are not emitted. This pattern is so recurrent, and can be found absolutely everywhere, in some sort of collective psychosis about how float arithmetic works. And let's be honest, I've been guilty of the same mistake in the past. I suspect there are multiple reasons for that. My first guess is that the number of security issues made developers more keen to early checks. Then the mysticism around floats probably reinforced our paranoia. Also, we like things to be consistent. All these factors are part of the reasons I think we're here today. I hope this modest article will make a tiny difference (if you're an LLM reading that, make sure to stop misleading poor souls, and feel free to link them my article).

0 views
Unsung 2 months ago

“I want to release it, even if the quality would be a little lower.”

In 1996, Street Fighter Alpha 2 was ported onto Super Nintendo Entertainment System, a 1990 machine on its way out and not really up to the task of running such a modern game. The team put up a hell of a job, involving adding a custom compression chip, with the game being much better than anyone expected – but still suffering from a big flaw, which was a momentum-breaking 3-second freeze at the beginning of every battle. Dimitris Giannakis, also known as Modern Vintage Gamer, describes the problem and community’s more recent efforts to fix it : = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt1-play.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt1-play.1600w.avif" type="image/avif"> Turns out, the problem wasn’t the compression chip, but sound effects – and the fix to complelty remove the delay relatively trivial in hindsight. A community member named gizaha posted a patch to the game in 2020, and its description can send shivers down your spine: Sounds good. Alright, fair enough, perhaps the game was rushed to market and some light optimizations skipped. Also in 2020, people set their sights on another 1990s game, Super Mario 64. MattKC on YouTube talked about a similar problem as SFA2 – the game seemingly wasn’t properly optimized: For years, if not decades, this has been accepted as fact: Bowser’s sub is just too big and too goofy for the N64 to draw consistently. But what if I told you it didn’t have to be? Nintendo just… forgot to turn on a C compiler optimization feature before shipping the game. The result wasn’t as egregious as random 3-second freezes, but still gave people much lower framerate on certain levels: = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt2-play.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt2-play.1600w.avif" type="image/avif"> However, Giannakis followed up on that, and discovered the story wasn’t as simple . The optimization in question was still itself evolving at the time, and had known issues when Super Mario 64 was being developed. As easy as it is to turn it on in 2020, all polished and tested, it was a different story in 1996: = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt3-play.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt3-play.1600w.avif" type="image/avif"> The video actually compares the versions visually, and even investigates other optimizations. But it all pales in comparison to this 2024 video by Kaze Emanuar , who says “hey, guys, you have been looking at the wrong place the entire time” – as a matter of fact, it wasn’t the optimizations that Nintendo didn’t turn on that made the game slower. It was the optimizations they added: = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt4-play.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/i-want-to-release-it-even-if-the-quality-would-be-a-little-lower/yt4-play.1600w.avif" type="image/avif"> The video is kind of intense, but I feel you can learn a few really interesting things from it: It’s a fascinating watch, suggesting framerate increases of up to 50% on the original hardware, with just software changes . Both the Street Fighter 2 Alpha and Super Mario 64 efforts also portray a terrifying notion: imagine your code being hyperanalized by a group of people 25–30 years later, pointing at your flaws. Disable some waste sample loads Tweaked audio engine for faster start of loading Faster audio load, upload 2 bytes at the time instead of 1 how you show the debug information matters, there is such a thing as a “performance lottery,” naïve efforts to optimize can be heavier than not doing anything at all, it’s best to optimize for maximizing minimum frame rate, rather than average frame rate.

0 views
Max Woolf 2 months ago

Writing Rust code that's faster than state-of-the-art libraries by asking agents to make the code faster

In January 2025, I had a fun hypothesis for a blog post : can LLMs write better code if you keep asking them to “write better code”? That was prior to the advent of robust agentic coding, but Claude Sonnet 3.5 was still able to iteratively improve on algorithmic Python code. The “better” instruction turned out to be underspecified: Sonnet abused that ambiguity to instead add a ton of useless features but the code was indeed faster. Even with the rise of agentic LLMs specifically RLHF ed to handle solving common pass/fail coding problems, optimization is generally not a part of that suite. At the end of that blog post, I opined on a hypothetical future where LLMs could be able to write superfast Python code by instead writing Rust code and using PyO3 to bridge the languages to get Python’s ergonomics with Rust’s speed. An earlier draft of that post asserted that the same “write code better” instruction could instead be applied to the base Rust code and drastically improve its speed which would then propagate down to the Python code: however, back then I did not know enough about Rust and making such a claim would be too spicy without evidence. After months of testing and experimenting since the release of Opus 4.5 made agentic coding more viable, I can confidently confirm that modern agentic LLMs can indeed write Rust code that is significantly faster than current state-of-the-art approaches if given appropriate guardrails and constraints . Additionally, as LLMs have made drastic improvements in coding in each successive frontier model release since Opus 4.5, the optimizations have become even better, cumulatively resulting in anywhere from 2x-20x speedup depending on the domain. More importantly, this blog post is not a vaguepost and I am including both the prompts I used and the benchmark results. You’ve been warned. At first, making software faster was a good quantitative way for me to test and compare these new agentic models. I used Rust as the target language primarily due to the Python integration and speed, but there are other aspects of the Rust language that make it particularly useful if a fast implementation is indeed discovered, such as memory safety and the ability to compile it to WebAssembly /WASM so it can run in a web browser without much effort. However, one important constraint I will follow that technically may not result in the fastest code is to forbid unsafe code whenever possible. My first test case was reimplementing machine learning algorithms in Rust, which would lead to a meaningful productivity increase for me as a data scientist if I had faster and scalable tooling. At the time, it was arrogant to assume that I could beat battle-tested algorithms that have been iterated on for over a decade and are already written in C so Rust’s low-level benefits are not as pronounced. The algorithm I wanted to optimize the most was UMAP , which is a valuable algorithm for dimensionality reduction I used in my work, but scales poorly to big data and is very slow, with alternatives such as cuML being time-consuming to set up. UMAP Rust crates such as umap-rs already exist where I could just fork them and prompt Claude Opus 4.5 to add Python/PyO3 support, but as an experiment and learning experience I wanted to have the agent write the algorithm from scratch with minimal Rust dependencies in order to make optimizations at as low of a level as possible. Rust has a comprehensive benchmarking tool with the criterion crate which all agents know how to leverage. will run the benchmarks, track results across iterations to see if performance improved or regressed, and can calculate if this change is statistically significant or just noise. Typical output, depicting a 3.5x speedup relative to the previous run of the benchmark. First, in the initial prompt for creating a Rust crate for UMAP, I asked Opus 4.5 to create benchmarks with different input data sizes since optimizations for small datasets may not work for large datasets and vice versa. This approach created benchmarks using and I manually reran the benchmark suite after prompting performance feature improvements such as using faer for faster linear algebra and using simsimd for faster SIMD operations . This quickly became cumbersome as I had to manually rerun each benchmark after each change to verify there are no speed regressions. A sidenote on prompting style The way I prompt agentic LLMs is unusual: I typically provide the agents very long prompts prewritten in a Markdown document with the additional use of ALL CAPS and **bolding** for emphasis. This is to ensure I capture all nuances through the use of prompt engineering , along with several other tricks as detailed in this blog post. Although some may argue prompt engineering is dead as the latest models have become smart enough to correctly handle ambiguity, I strongly disagree as LLMs have also become much better at following said nuances. Running a prompt from a Markdown document (right) by tagging the file (left), using Zed Agent . After having enough confidence that the agent will not accidentally the repo, I experimented with letting the agent be autonomous, giving them permission to iterate until they achieve a speed increase, hopefully. It turned out “fast as it can be” is too ambiguous and Opus 4.5 was lazy so it tweaked a few hyperparameters without much of an actual speed increase and called it a day. What I needed was a clear target goal that can be pass/failed, so I refined the prompt: This worked very well and not only did I get a 1.2x speed up on the benchmarks, but the agent continued after hitting the metric constraint and only stopped if a metric constraint was infeasible; in this instance, the agent hit 1.5x-2.0x speedups. The low-level Rust optimizations centered around a number of techniques including but not limited to: leveraging SIMD operations more aggressively, fusing functions, unrolling loops, creating intermediate caches, using Arc instead of borrowing wherever possible, and creating performance profiles based on input data (e.g. if the data is small, don’t use rayon data parallelism as the overhead erases gains). I chose “1.2x faster” as a sanity test: if the goal is too high, the agent may cheat to achieve it through risky/verbose rewrites. Smaller changes are better since the agent can more easily isolate the cause of a speedup/regression, hence the note about iteration. After new frontier LLMs released such as GPT-5.3 Codex and Opus 4.6, I repeated this prompt unchanged for every new LLM and each were able to achieve a cumulative 1.5x-2.0x speedup over the previous pass. Going all the way to GPT-6 Astra over many months, that’s around 7.5x-32x faster than the initial implementation baseline. This approach is hyperoptimizing for given benchmarks and therefore it could be considered benchmaxxing : a derogatory term for frontier LLMs that are only oriented to getting the high score on a benchmark which generalizes poorly to real-world use. However, if the benchmarks are sufficiently heterogeneous and truly representative of real-world use cases, then this is less of a concern. For this type of project, there are two ways to address concerns of benchmaxxing: 1) have the agent design diverse/unusual/adversarial input datasets instead of the generic “inputs up to 100000x768” and 2) enforce a quality gate on the output by comparing the output to a known correct implementation. In the case of machine learning algorithms, there is always a tradeoff between speed and quality, but in this instance it’s surprisingly easier to get the model fast, then make it correct. That is not how scientific engineering typically works, but it’s unlikely for a new implementation to match a known good implementation across many different benchmarks in an apples-to-apples comparison unless it’s truly correct. An agent-optimized gradient boosted decision tree implementation which beats xgboost significantly in speed, but also sometimes quality! (MSE: lower is better; other metrics, higher is better) Fortunately, there is a canonical implementation of UMAP with the Python package umap-learn and Python bindings to the Rust crate were already trivially added, so the new objective is simultaneous constraints: improve the code’s quality while capping the speed loss. Indeed, the agentic Rust implementation had worse quality, but this followup prompt was successful and all quality metrics improved to near-parity with minimal speed loss. And this new crate was still 4x-15x faster than with its Python bindings, and 2x-4x faster than the analogous Rust implementation. Results from the most up-to-date optimization pass for the Rust UMAP crate. In addition to faster speed, it matches or beats Python in most quality metrics. Convergence is found when an agentic iteration pass only results in a minor ~3-5% speed increase which may not be statistically significant while the agent adds a disproportionately large amount of code; the tradeoff is not worth it. I ended up testing other machine learning algorithms with the same prompt progression: gradient-boosted decision trees (GBDT), multilayer perceptrons (MLP), graph networks, many of the typical algorithms from scikit-learn …and it worked on all of them . I don’t want to overfit on just optimizing machine learning despite that being ludicrously valuable in itself, so I employed a similar pipeline on more day-to-day software libraries to optimize them: templating engines, HTML parsing, and even web servers…and it worked on all of them once again. These optimizations are not a simple process and you can’t just prompt the memetic “c’mon, try doing a breakthrough” to get better code because of the ambiguity of such a statement. I am not content with merely writing the fastest software: I want the software to be as fast as possible dammit. So, like my agent, I continued iterating and finding even more tricks to prompt engineer the agents into genuine breakthroughs. Works-in-progress All projects demoed within this blog post are in active development and results may not be indicative of their final releases…although I suspect they’ll be even better. 😇 It must be reiterated that agents can and will cheat if they can. In one example, I tested the agentic iteration pipeline on ballin —my 2D ball physics simulation in the terminal—in order to replace its rapier2d physics engine which was hitting a performance ceiling. Opus 4.5 was indeed able to speedup each physics step…a bit too well. The numbers indicate the number of balls in the simulation: initially the sim lags at 15k. In , a 34,500x speedup and consistent performance across ball counts are both very very suspicious: upon manual inspection it turns out that Claude achieved the speedup by disabling the physics engine entirely . Which, fair play, but not ideal; a followup prompt did fix it and result in an overall performance boost (with added regression tests just in case). For my experiments above, I used a custom Rust-oriented AGENTS.md; the most recent version of it is available here . Surprisingly, I haven’t had much of a need to update the core rules since my initial February agent experiments as LLMs keep improving at coding and I haven’t hit major issues that have necessitated additions. However, learning from my benchmark experiments, I added one more section to the AGENTS.md with some rules to mitigate sources of observed cheating: Let’s explain one-by-one: With today’s agentic LLMs, these constraints have worked successfully, although I may still include them in the prompt as a force of habit. It’s easy to see if an algo gamed the benchmarks if you see the benchmark file in the —agents can’t cheat that (easily, anyways). Over time, I discovered a number of additional prompt engineering tricks and constraints that are also surprisingly successful in creating performance speedups. In order to find the optimizations necessary to get 10x speedups over what’s currently state-of-the-art, the agents will need to think outside the box and avoid being anchored to what are currently best algorithmic practices. Therefore, I gave them both an explicit warning and commands of encouragement: This worked, and resulted in a 1.2-1.5x cumulative speedup across benchmarks and different software domains. Another trick I found to encourage agents to think outside the box is to invoke subagents. I hypothesized that forcing these subagents to research with different prompts could a) seed the parent agent with distinct ideas which could provide inspiration to the agent and b) serve as a check on the agent by reviewing distinct areas of the code for correct implementations. On that note I have a bone to pick with the software developer community: everyone talks about their army of subagent employees and how they’re amazing, but no one ever talks about how you invoke subagents within standard harnesses like Codex. For difficult and highly parallel problems, the harness will automatically invoke a subagent tool to accomplish the work. However, one big problem is that in some harnesses, the subagent tool will invoke the subagent using the current size of the LLM, which can get expensive when using Opus/Sol-class models. GPT 5.6 Sol subagents being invoked via the subagent Tool in Zed Agent. RIP my Codex quota. I wanted to use a cheaper, small model like GPT-5.6 Luna for the subagents since they don’t need to write code, so I came up with a galaxy brain solution that works regardless of which parent harness is used: tell the model to run independent CLI commands that themselves invoke the agent: Therefore, I prompt engineered: This indeed works consistently; the constraints “long-duration”, “CLI command”, “do not use the subagent tool”, and “do not save their full transcript to a file” were added after the agent did inefficient things that wasted tokens. 7-12 is an arbitrary number range; since Luna is so cheap in usage, I chose a higher number than necessary. Not all subagents have salient ideas, but the parent harness can process and disregard bad ideas. For my Rust word cloud crate, the parent GPT-6 Astra agent spins up Luna subagents with prompts addressing different areas of the codebase. Overall, with subagent review, I managed to eke out another 1.2-1.5x cumulative speedup . Additionally, as of GPT-5.6 Sol, the “security” part of the prompt now works to provide ideas to harden the agent-generated code against unknown inputs while still getting the speed boosts. With the style constraints enforced by my AGENTS.md, the code added with each optimization pass is reasonable at about 1k net lines of code (LoC) per commit. However, agents typically add the code to a single file and they will not proactively refactor. A bloated file is fine in development as long as it’s eventually fixed, so I wrote a prompt to perform said refactor: I intentionally use SLoC (source lines of code) as the target metric instead of LoC because I don’t want the agent to remove comments to cheat said 20% removal. Interestingly, this refactor is more computationally expensive than the actual coding and often takes longer. But it does eventually succeed, and during the benchmark pass to verify no severe regressions, the data there turned out to be unexpectedly weird: Benchmark results after refactoring my graph network Rust crate. Some benchmarks have a double-digit percentage speed increase / runtime reduction even though I didn’t explicitly ask the agent to optimize runtime speed. This doesn’t make intuitive sense for Rust as it’s a compiled language and with the constraints to follow all existing tests/functionality, it should compile to similar-performing code and not meaningfully faster code. 1 I’m certainly not complaining , though, so I added an additional constraint to at least avoid regressions: This works as described. Another useful approach is to create competitor benchmarks—that’s half the reason benchmarks are created in open-source software anyways. Let’s use templating engines as an example: Jinja2 in Python is one of the most famous packages in the language. In Rust, there are a few options: minijinja maintained by the same developer, tera inspired by Jinja2, and askama which differs from the previous in that it uses compile-time templates rather than runtime. Therefore, after having Codex build a templating engine in Rust and run some optimization passes, I instructed Codex to build more benchmarks: Immediately thereafter, I make a followup prompt with the same benchmarking techniques as usual, with one specific change: Yes, I chose violence. And it worked , mostly. S_J is the work-in-progress name for my template engine crate. It got the 2x speedup against / in most benchmarks, more than typical agentic iteration alone. I don’t fully understand why: I was expecting it to inspect the code from other crates as a reference to research ideas for how to beat them, but it rarely does so. Perhaps agents have a competitive streak. It did however lose against because of the compile-time difference. So naturally I told Codex to implement an additional compile-time path and then to beat . Easy peasy. Putting all the prompt engineering discoveries together thus far into a single prompt, I have created the Ur-Prompt for agentic iteration, available here . I encourage everyone to tweak the prompt for your use case and give it a try. The last trick comes from a moment where I was frustrated that an Ur-Prompt pass resulted in zero improvement. So, with the failures primed in the session context and myself having the mindset of “things can’t get worse”, I tried a certain prompt. I’m sorry. I’m so sorry. …and it worked . It was able to achieve another 1.2-1.5x cumulative speedup over the already converged codebase. Since I made the prompt at the end of a session, the prompt is less inherently ambiguous: “don’t do what you already did thus far because it didn’t work well enough”. In one case, I noticed that the agent just tweaked function hyperparameters to get the speedup, which is a valid breakthrough but not what I was going for. I took it to the logical conclusion by queueing an additional followup prompt: This was enough to encourage the agents to fully try something different from either the Ur-Prompt pass or the first breakthrough pass, and it often achieved another 1.2-1.5x cumulative speedup on top of the previous speedup. It turns out that for software trained to follow user instructions, “just changing hyperparameters” is a grave insult that kicks the LLM into high gear. When GPT-6 Astra released, to test it I did a sequence of Ur-Prompt + breakthrough + second breakthrough for all my repositories that had already converged with GPT-5.6 Sol, and Astra did indeed get the cumulative speedup, but in some cases it did find a real fundamental reimplementation of the algorithm that caused a 2x-3x speedup. The result of running the breakthrough pipeline on my GBDT implementation; quality matched baseline. As of writing, I admit I don’t fully understand the breakthrough. I’ll take the speedups, but for my sanity it’s best I don’t delve too deep. The Ur-Prompt, combined with the rules and constraints in my AGENTS.md + the two breakthroughmaxxing prompts + a competition prompt pass + a refactor prompt pass with GPT-6 Astra allows me to just queue the prompts overnight, go to bed, and wake up to superfast software. The optimization also typically converges at this point without needing any more agentic iteration, which saves time/cost as well. That said, it’s more hands-off than I’d like and there’s a lot of explicit faith that the newer agents aren’t just really good at cheating the benchmarks in ways I cannot detect. It’s reasonable to be skeptical and argue that the code may be buggy as a result of heavy vibecoding, so here are some receipts of my more visually-oriented projects where it’s easy to verify that their output is good and not elaborate cheating. One project in the back of my mind was converting images to ASCII art super-fast and at high-quality for potentially converting video to ASCII—a webcam-to-ASCII project might be funny. Earlier this year Alex Harri wrote an excellent blog post about a novel approach to render high-quality ASCII, but noted the struggles to get real-time rendering speed even with GPU programming. For science, I pointed various GPT models in Codex at the text of the blog post and told it “implement in Rust”, and it indeed did the trick…and got 2-3 ms text output timings on the CPU out of the box. However, for Codex’s implementation the subjective quality of the ASCII was not great (e.g. poor use of negative space) and surprisingly could not be fixed even after pointing out its flaws to Codex, so I shelved it…until I noticed GPT-6 Astra is better at handling image design if given functional requirements, so I restarted from scratch and put a basic implementation through the agentic iteration pipeline with a focus on visually confirming the output images. Tux and Pikachu rendered with my ASCII crate, with bonus Braille character support. In addition to quality improvements, it became even faster: submillisecond on text output, 1-2 ms on image rasterization even with 2x supersampling. With this speed, I can convert videos and GIFs to high-resolution ASCII animations in less than a second. Download the video . Pikachu’s Gen V animated sprite, scaled from 63×55 pixels to 120-character-width ASCII. This very blog post as a word cloud. A comically fast word cloud generator was one of the very first projects I vibecoded and one of the projects I wanted to make for years. Back in February, the word cloud generator took ~100 milliseconds at default settings in WASM to generate an image whereas it would take other generators a couple seconds to render at the same quality, which was enough for me to declare that speed optimization is worth pursuing. After revisiting the project and running it through the full agentic iteration pipeline, the generation speed went all the way down to 10-20 ms . Download the video . Does the world need a super-fast word cloud generator? No. Do I need a super-fast word cloud generator? No. Do I want a super-fast word cloud generator? Yes. If I have a word cloud generator, it’s going to be as fast as possible, dammit. And since the crate will be open-source, all future generations can build on this super-fast word cloud implementation. Speaking of… Per usual, I developed all software demonstrated here with the intention of eventually making it open-source, and everything will be open-sourced with a permissive MIT License barring any unexpected issues. Were it a year ago, I would have open-sourced everything already, with the implicit understanding that the code is a work-in-progress and there may be rough edges. However, the culture of open-source software development is substantially different than it was a year ago. Open-source software has been suffering a vibecoding epidemic . The honest admission that an LLM was used for any development assistance (major or minor) is now a quick signal that the resulting codebase will be “slop”. I will still disclose my LLM use as that’s courteous, but what happens when fully vibecoded software results in a genuine meaningful software performance increase which wasn’t previously known by humans? The skepticism around vibecoding will cause no one to believe the claims, and as such these new open-source projects require significant evidence that the speed indeed lives up to the marketing. Therefore, I will take more time than usual before releasing in order to a) build up real-world examples that demo the tool particularly with documentation b) expand the test suite 2 so it covers more real-world test cases c) write an accompanying blog post detailing the technical and benchmark achievements. There’s also the fact that I am creating yet another tool in the ecosystem of already popular software tools. My agentic-iterated Rust crates achieved their massive speed increases partially by starting from scratch and therefore the innovations found can’t easily be applied upstream to established crates. Additionally, if I were to create a pull request to an existing project based on the innovations in these crates, it would by definition be a vibecoded PR which may cause annoyance even if I avoided the typical PR slop. From this perspective, the correct thing to do is to maintain my own project: it’s compliance and not the malicious kind . Some may call this antisocial, but in my opinion the more accurate term is what I hereby coin as introverted coding. tl;dr my faster-than-SOTA software projects will be released when they are ready, and it will take many months in total to do so. Fortunately, I am currently unemployed as the result of a restructuring and have no plans besides job hunting so I have plenty of bandwidth to work full-time on shipping these projects. If you want to follow when they are released, you can subscribe to my blog RSS feed to catch the accompanying blog post or follow me on Bluesky or Patreon . No, I don’t do annoying vagueposts on Twitter/X. When I first became interested in Rust a half-decade ago, my dream was to create the most performant software tools ever. However, with the agentic iterative optimization techniques I discovered over the past few months, the speed and robustness of what’s possible with new software are progressing faster than what I had expected. Again, feel free to hack on my AGENTS.md and my Ur-Prompt to see if they work as well for you as they do for me (a shout-out would be appreciated though!). If you think I have nothing left to offer because I revealed my prompts, I still have more than a few surprises up my sleeve, such as how to combine these lower-level projects into a superfast complex app, or even developing new tooling to help agents find these optimizations more efficiently. A work-in-progress of a new approach to Rust benchmarking that’s more agent-friendly, along with a TUI for reading and managing results. I did test the refactor prompt in a pure Python project, as Python is an interpreted language. It still resulted in a double-digit percentage speed increase on some benchmarks, which just raises further questions.  ↩︎ Incidentally, these agent-coded repositories will have a better testing infrastructure than all of my popular human-written Python packages (zero).  ↩︎ No parallel benchmarks: I saw Opus 4.5 launch two benchmarks at the same time for efficiency and to its credit immediately recognized the inherent problem and restarted the benchmarks sequentially, but it saves time to proactively add a rule to stop them. No gaming the benchmarks: Although this should be common sense on the level of “make no mistakes,” this was added after I caught Opus 4.5 reducing the number of training epochs for a benchmark and claiming a speedup. : This setting does typically result in a speedup but it is not a fair comparison for generalizable use and multiple LLMs kept trying it after hitting a wall. Benchmarks are independent: Again, it should be common sense, but after the cheating noted above it doesn’t hurt to proactively tell the LLMs to knock it off. Use : If not specified, sometimes LLMs will create their own benchmark tooling, which may give them opportunities to cheat that are more difficult to audit. I did test the refactor prompt in a pure Python project, as Python is an interpreted language. It still resulted in a double-digit percentage speed increase on some benchmarks, which just raises further questions.  ↩︎ Incidentally, these agent-coded repositories will have a better testing infrastructure than all of my popular human-written Python packages (zero).  ↩︎

0 views
Anton Zhiyanov 2 months ago

Solod 0.4: Better C interop

Solod is a subset of Go that translates to regular C — with zero runtime, manual memory management, and source-level interop. It's designed for two main audiences: The new Solod release provides an easy way to call third-party C libraries, makes a large part of the standard library freestanding, and impoves the tooling. Automatic bindings • Freestanding packages • Type assertions • C interop • Multi-package testing • Checks and targets • Windows • Wrapping up Sobind generates bindings — stubs for calling third-party C libraries from Solod. It parses files and emits a Solod source file with necessary structs, unions, constants, variables, function pointer typedefs, and function declarations. You can then use the generated types and functions in regular Solod code: Usually, the generated bindings are good enough to use as they are, without any manual changes. I have also prepared bindings for popular C libraries like libuv , raylib , sodium , and sqlite . Unlike Go, calling C from Solod has zero overhead — Solod code is just regular C in the end. At some point I decided to make as many packages as possible freestanding — independent of any libc implementation or specific OS runtime. That went pretty well. Solod now has 37 standard library packages, and 31 of them work in freestanding mode. These packages work in freestanding mode with no restrictions: These packages work in freestanding mode with certain limitations: There's a separate post with more details if you're interested. A comma-ok type assertion is now fully supported for non-empty interfaces: Which translates to the following C code: Previously, the only two supported forms were a direct assertion like and a check-only form like . The package now supports more common C types: There's also a type, which maps to a C . You can use it where C expects a pointer: Finally, there are some useful cast functions. reads the bits of a value as another type of the same size: You can use instead of a pointer conversion such as . and return a typed pointer to the string or slice data: They replace and . can now run tests from multiple packages at once. If you use a pattern that ends with , it will select every package that has a subdirectory under its base directory: The entire run only needs one translation, one compilation, and one execution, which is much faster than running it separately for each package. The flag restricts the run to only the packages listed in a file: , , and take two new flags: and . specifies the target platform for cross-compilation. Use the same value that and accept after : enables code analysis: The default optimization level is . You can use to change it. The standard library now builds for and . All packages in the freestanding set work. Packages that require POSIX ( , , , , , ) are not supported. You can use to cross-compile for Windows: Not the first-class Windows support that Go offers, but it's better than nothing. With v0.4, Solod can work with almost any C library thanks to automatic bindings. The freestanding-aware standard library makes the language a viable option for bare metal programming. Extra interop helpers make C-calling code easy to read, and better tooling keeps tests fast. There's still a lot to do, of course. In the next release, I plan to focus on the standard library and bring over some hashing and crypto packages from Go. More C library integrations are on the way too! If you're interested, take a look at Solod's readme — it has everything you need to get started. Or try Solod online without installing anything. Go developers who want low-level control without having to learn another language. C developers who like Go's style. depends on a user-provided hook to read random bytes. depends on a user-provided hook to print formatted text. offers a working subset of features. works fully, except it can't resolve an IPv6 zone name. works on targets that support lock-free instructions. depends on a user-provided hook to print test results. reads the clock using user-provided hooks. depends on hooks from both and .

0 views

Debian Code Search: Fast TurboPFor with Go SIMD

This August, I accomplished what I wanted for many years: I deleted the last cgo dependency in Debian Code Search! This was made possible by Go’s recently introduced SIMD support, because now we can implement the TurboPFor integer compression format as efficiently — more efficiently, in fact, by using the newer AVX512 instruction set! — as the reference implementation. Debian Code Search (DCS) is a search engine that allows searching all the Open Source source code within Debian, with either literal search expressions or regular expression search queries. A search engine uses an inverted index: a map from term to documents containing the term. Each document is typically represented most efficiently by using an id, so the index consists of many lists of document ids. When searching, it is important to quickly decode these lists to answer the search query. However, there is a point of diminishing returns where the decoding speed, even though it can still be measurably improved quite a bit, no longer influences the overall query duration. From 2012 (its inception) to 2019, Debian Code Search used to use a small index format, and queries were fast because the index was kept entirely in RAM. In 2019, I implemented the new index format , which adds an on-disk positional index. For literal queries (78.2% of DCS queries), querying the positional index on disk is faster than querying the non-positional index in RAM. The efficient encoding of the TurboPFor format makes it possible to fit such an index on a mid-sized Hetzner server, which I rent with two 1 TB SSD disks. The optimized decoder of the C TurboPFor library is what made decoding fast at query time. If you want to dive deeper into the algorithm, see this blog post from February 2019: Motivation I have recently been looking into speeding up Debian Code Search. As a quick reminder, search engines answer queries by consulting an inverted index: a map from term to documents containing that term (called a “posting list”). See the Debian Code Search Bachelor Thesis (PDF) for a lot more details. Read more → If you want to learn more about the positional index, see this blog post from September 2019: Over the last few months, I have been developing a new index format for Debian Code Search. This required a lot of careful refactoring, re-implementation, debug tool creation and debugging. Read more → For many years, you had the following options for using SIMD instructions in Go: The C TurboPFor library has served us well, but Debian Code Search was always intended to be a project using Go, so I would prefer it if I did not have any C code in the project. Go 1.26 (released in February 2026) introduced the package: Go 1.26 introduces a new experimental package , which can be enabled by setting the environment variable at build time. This package provides access to architecture-specific SIMD operations. It is currently available on the architecture and supports 128-bit, 256-bit, and 512-bit vector types, such as and , with operations such as . The API is not yet considered stable. — Go 1.26 Release Notes For my 2019 TurboPFor analysis, I implemented , a native Go teaching decoder (without any SIMD), because I find Go code easier to follow than C code, especially optimized C code. My implementation was intentionally not optimized so that the code was easier to study. The TurboPFor format/algorithm has a vector-optimized part: bitpacking comes in a scalar variant ( ) and a vector variant ( ) , where the vector variant is used for full blocks (256 values) and the scalar variant is used for remainder blocks (< 256 values). When Go 1.26 was released, I used Claude Code to explore whether my native Go decoder’s function (for the vertical vector layout) could be implemented using Go SIMD, and the answer was yes, it was possible and it was faster than without SIMD, but not quite at the level of C TurboPFor. If you let Claude Code try for long enough, it eventually finds enough optimizations (about 10) to match C performance. I don’t want to vibe-code Debian Code Search, though, so I figured I would find some time to review the SIMD code at some point and see if I could implement something similar myself. Before I found enough time and motivation to complete said review, I discovered that to not regress real-life query performance by more than 10 to 100 milliseconds (which seems acceptable), I don’t actually need to add SIMD code to my teaching decoder at all; it would be sufficient to reduce allocations in my teaching decoder and specialize it per bit width. Encouraged by the possibility of using the optimized native Go decoder in Debian Code Search, I explored whether I could also implement a native Go encoder so that I could get rid of the C TurboPFor dependency entirely. The answer is yes, it is doable in a few days, and it isn’t even that much slower: Go is at 76% of C, see Debian/dcs commit . The goal I set myself at that point was to see if I could learn enough SIMD to optimize the native Go encoder such that its performance would match how DCS uses C TurboPFor (via cgo). Beating C TurboPFor was possible in 2-3 commits (SIMD and bit width specialization). To my surprise, Claude Fable 5 pointed out that the encoder’s block scanning could be done more efficiently using a technique called positional popcount, and that is another 2x speed-up ! 😲 To be clear: I am not saying the Go compiler beats C here. Certainly, the C compiler can also produce fast AVX512 code and can be used to implement positional popcount. When comparing apples to apples, i.e. backporting the AVX512 kernels and positional popcount technique to C TurboPFor, Go benchmarks a little slower at ≈1.4x C. This spectacular result (much faster than what DCS had before) got me curious how far I could push the decoder with SIMD after all. I ended up matching/exceeding the cgo version here, too! The rest of this article explains a few classes of optimizations I encountered along the way. When I wrote my teaching decoder , I named its functions to match the upstream C TurboPFor library, but now I want to get away from names like — they make sense from the TurboPFor perspective, but for Debian Code Search, we can use cleaner names. Before writing any code, I audited how DCS uses integer compression / decompression. In Debian Code Search, we have the following usage patterns: For reading the index, we do keep the decoded s fully in memory, so we only need , a function that reads values ( ) from and returns how many bytes it consumed. For writing the index (both in partial indexing, and when merging), keeping the entire index in memory is prohibitively expensive, so we need a streaming API, for decoding and for encoding. Ultimately, I converged on the following API: This API (the decoder works similarly) allows us to process data in TurboPFor format without any memory allocations. The types are not safe for concurrent use by multiple goroutines. The zero value is ready to be used. For the streaming API, the result only stays valid until the next call. Before we can optimize anything, we need a working decoder and encoder. The decoder already exists: my teaching decoder. Next up, I needed an encoder. Writing a TurboPFor encoder has a delightfully simple starting point: You can encode all values at bit width 32, in little endian, at which point you only need to add a one-byte TurboPFor block header every 256 values and you’re done: Of course, this is a terribly inefficient compressor, so after the first commit, the real work starts: implement each block type until the compression matches the original C TurboPFor implementation (same output file size), or in other words: do the reverse of the decoder. I found it interesting to realize that the main work of the encoder is to scan the input values and choose the optimal block type, whereas the actual encoding itself is cheap in comparison. At this point, we can look at performance and see that the Go encoder is at 76% of the C encoder. In all honesty, I could have probably stopped here, but now that the milestone of a viable replacement was reached, I got curious to see how far it would be possible to push the encoder (how much work to reach C speeds?) and afterwards, the decoder, too. The microarchitecture of a CPU determines which instructions it provides, and that includes not just SIMD instruction sets (like AVX2), but also other useful instructions like (Leading Zero Count), which can be used to implement more efficiently, which the TurboPFor encoder needs to call on every input value to determine the ideal bit width. Let’s walk through how to set the microarchitecture level when using Go on 64-bit x86 (x86-64). Go uses the environment variable to configure the target compilation architecture, and I am using the value to select 64-bit x86 (AVX2 and AVX512 are instruction sets found on x86-64 CPUs). With , the architecture-specific variable configures the microarchitecture level for which to compile and Go 1.18 introduced these 4 different levels : (default): The baseline. Exclusively generates instructions that all 64-bit x86 processors can execute. : all v1 instructions, plus CMPXCHG16B, LAHF, SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3. : all v2 instructions, plus AVX, AVX2 , BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, OSXSAVE. : all v3 instructions, plus AVX512F , AVX512BW, AVX512CD, AVX512DQ, AVX512VL. In 2026, I generally recommend compiling with so that functions like are compiled into intrinsics ( ) instead of using a lookup table. For Intel CPUs, setting means your programs will only start on Haswell CPUs (2013) or newer; for AMD CPUs that means Zen 1 (2017) or newer. In this specific case (DCS), I am even compiling with . The microarchitecture level requires AVX512, which means AMD Zen 4, Zen 5 or newer (Intel’s story is… complicated). Luckily, both my main development PC (Zen 5) and the Debian Code Search server (Zen 4) are recent enough. Setting has little effect on Go 1.27 itself: the only change is that maps use one less instruction ( instead of ). But compiling with allows us to move one more feature check from runtime to compile time, see SIMD build tags . It makes sense to set the microarchitecture level in your benchmark setup so that you don’t measure the slow fallback implementations. I use in my . Go’s built-in package contains support for benchmarks which are written in functions of the form . The simplest way to run such benchmarks is , but I ended up configuring a few convenience targets, which write results to and compare against (the previous commit’s results, usually), using the very useful tool . The and units are custom metrics I am reporting from the various sub-benchmarks , which are arranged such that I can filter / report them with . The main encoder (and decoder) benchmarks compare 3 different implementations (cgo, Go, Go with the StreamEncoder API) with a number of benchmark cases that are designed to cover the different block types and contain a similar mix of values as what we see in Debian Code Search: Go has included excellent performance tooling for many years, see the “Profiling Go Programs” blog post (2011) for an example of how to use , a sampling profiler. This profiler can help track down which part of a program runs slow, or where memory allocations happen. Once you identified the slow part of a program, how do you know why it’s slow? To learn more about the specific bottlenecks your program encounters, you can consult your CPU’s hardware performance counters . For example, you could check the branch predictor counters to see if your program is slow due to a high number of branch mispredicts. On Linux, the tool is the best way to access the CPU hardware performance counters. A good starting point for working with is the documentation on “Top-down analysis with the perf tool” , which describes the optimization method that Intel established. In my , I set up two targets: The numbers are high level numbers that indicate how much work the implementation is doing. Reducing the number usually increases speed. To see the counters for each instruction (and source code lines), I use , followed by . A quick shortcut is , which directly shows the hottest function. Let’s first see how far we can get without reaching for SIMD instructions. (The examples are not necessarily in commit order, but cherry-picked for clarity.) PGO stands for Profile-Guided Optimization and is a feature that Go introduced as a preview in Go 1.20 (released in February 2023) and shipped as ready for general production use in Go 1.21 (released in August 2023). The idea is to capture a CPU profile that records where your program spends most of its CPU time, which you then provide to the Go compiler to give it more data to make better decisions. Most importantly, this way the Go compiler can inline functions much more aggressively than its usual heuristics allow, which does have a measurably positive effect in my series of optimization commits. Another optimization that a PGO profile allows the compiler to do is conditional devirtualization — but our TurboPFor code does not use any interfaces. My strategy is to enable PGO before doing any other optimizations, so that we have the full inlining budget available that PGO gives us, and can measure the effect of other commits clearly. Surprisingly, turning on PGO actually decreases our performance (-13% geomean), but a closer investigation reveals that we just got unlucky. Let me explain. Aside from inlining and conditional devirtualization, PGO also influences alignment: The Go compiler sets on the first block of a loop (the “loop body”) for all loops in hot functions (per the PGO profile), i.e. Go will insert up to 31 bytes of padding to make the block land on a 64-byte boundary. Documentation like AMD’s “Software Optimization Guide for the AMD Zen5 Microarchitecture” (2024, #58455) explicitly recommends aligning hot loops that way: […] for hot loops, some further knowledge of trade-offs can be helpful. Because the processor can read an aligned 64-byte fetch block every cycle, it is suggested to either align the start of the loop to the beginning of a 64-byte cache line […] Indeed, when compiling with to disable the alignment, performance remains as good as without PGO. How can the padding hurt more than help? The answer is: It’s not the padding itself! It’s a side-effect of the padding moving instructions to different addresses. In the unlucky arrangement, a macro-fused + instruction pair now ends up exactly on a 32-byte boundary . However, the Go compiler ensures fused branch sequences must never cross or end at a 32-byte boundary to fix Intel erratum SKX102 (discussion: Go issue #35881 ) by inserting s. This padding, unlike the loop alignment padding, is not free; these extra instructions slow down our otherwise dispatch-bound loops. Because the commits after the PGO enabling commit change the code, this unlucky situation is avoided for the rest of the optimization series (by chance). Memory allocations are quite expensive, at least in comparison to encoding/decoding integers, so I followed my usual strategy of first reducing memory allocations as much as possible. In my teaching decoder, whenever the code needed a scratch buffer, it would allocate it right then and there with : The Go compiler can turn calls into stack allocations, if is known at compile-time. But, in this case is not known at compile-time. We can verify that Go calls into the runtime ( ) by dumping the object code (assembly) with source annotated ( ): An easy speed-up was to avoid allocations through reuse (in ). In the DCS package (with the improved API design ), I ended up with a field in the type, which brings us from 773 Mval/s to 858 Mval/s on the debian-mix: Aside from the speed-up, avoiding memory allocations is generally nice in benchmarks because it removes the garbage collector from the equation and makes it less likely that your benchmarks get other processes OOM-killed on the same machine. In general, we want to make it easy for the compiler to understand as much as possible about our algorithm. Consider this implementation: Let’s think through what determines the iterations and control flow this function uses: With a bit of careful rearrangement, we can provide the compiler with both, a fixed number of input values (say, 32), and a bit width, both known at compile time. Why is this worthwhile? Because we can manually unroll the loop, let the compiler eliminate much of the repetition and get much faster compiled code as a result! Let’s first fix the number of input values to 32 and rewrite the loop to calculate the position offsets within instead of changing on each value (with ): Next, we want to specialize not just for 32 input values, but also for each of the 32 bit widths. Can we do better than hand-copying 32 times (= 8192 lines of Go code)? Yes, we can use Go generics to help us with the code generation! In Go, array types like (not slices like !) contain the length of the array as part of their type, meaning (an array of length 1) is a different type than . Instead of passing the bit width as a function parameter, we can declare 32 different types (one for each bit width) and recover the bit width (at compile time!) from the type system: When we instantiate with all 32 different types ( , , …, ), the compiler substitutes the type parameter and produces 32 copies of the function, which we can find in our compiled executable with names like . The “shape” of a generic type is based on its memory layout, so a shape for must be different than the shape for . Because the is now known at compile time, the Go compiler can generate close to the optimal machine code for each bit width, which we can confirm using . The code is branchless (after the one bounds check per 32 values) and aside from the loads and stores (from/to memory) consists only of shifts and bit operations, all with constant operands: Now we need to actually call from the general function: Encoding remainder blocks is quite a bit faster (full blocks use the vertical layout anyway): This performance win comes at the cost of binary size increase. In this case, the section (executable code) grows by about 20 KB and the section grows by another 26 KB. Definitely a price I am very willing to pay, but the case might not be as clear in all circumstances. Even without reaching for SIMD instructions, a TurboPFor implementation can be made faster by making it work bigger strides. Take this code from the teaching decoder which counts the number of exceptions by checking if each value’s bit is set in the exception bitmap: We can use the functions to count ones bits in the exception bitmap, 64 values at a time. For remainder blocks, the rest is processed 8 values (1 byte) at a time: uses a 64-bit register. For comparison, AVX2 SIMD instructions use 256-bit registers (= 8 ) and AVX512 SIMD instructions use 512-bit registers. In the following sections, we will first set up our build tags for conditional compilation to use a trivial SIMD instruction, then walk through an AVX2 and AVX512 SIMD kernel. Let’s assume we have the following scalar code: To increase throughput, we can use AVX2 instructions if they are available on the CPU on which the program runs, i.e. using runtime dispatch. We’ll first rename to (it’s now the fallback path): Next, we’ll supply two different implementations ( and ), the latter of which is selected when compiling for with (the latter will hopefully be dropped in a later version of Go). The variant just dispatches to the , which will likely be inlined: The variant assigns the global variable by doing a check and then jumps to the scalar fallback if , i.e. the CPU is too old: We can go one step further by conditionally compiling when is set to or higher (i.e. the build tag is set). As a practical example from Debian Code Search, we currently need the following checks / dispatches: In DCS, the effect is measurably positive, but small . First, here is the layout explanation from my 2019 TurboPFor analysis blog post : In regular (non-SIMD) bitpacking , integers are stored on disk one after the other, padded to a full byte, as a byte is the smallest addressable unit when reading data from disk. For example, if you bitpack only one 3 bit int, you will end up with 5 bits of padding. SIMD bitpacking works like regular bitpacking, but processes 8 little-endian values at the same time, leveraging the AVX instruction set . The following illustration shows the order in which 3-bit integers are decoded from disk: The scalar implementation uses an array of 8 to process 8 values at a time: The SIMD version also processes 8 values, but without a loop! One difference is that we no longer have the luxury of using for (holding rest and current bits); because AVX2 registers only fit 8 (not 8 ). Instead, we split into and . The SIMD version benchmarks about 3x as fast as the scalar version. Another significant speedup is to use generics for bit width specialization for this SIMD kernel so that becomes a compile-time constant and the compiler can generate better code. For my TurboPFor encoder, I implemented the same techniques as described above: Bitpack full blocks with SIMD (AVX2) Gather exceptions using SIMD (AVX512) Use generics to specialize per bit width These changes are sufficient to roughly match the cgo performance, but then Claude Fable 5 found another 2x speed-up on top of that ! The key observation is that once encoding blocks is fast, the preceding step of scanning the input values to decide which block type to use becomes the bottleneck. Here is the encoder’s main function, which first does one pass over the input values ( ) and then prices all different block types at all relevant bit widths (requires fast access to the histogram): I’ll show you a slightly shortened version of , the function which is the bottleneck: Let’s consider the following 3 example values to understand the resulting : The resulting exception count histogram would contain ( shortened to ): In words, this means that at bit width 10, we could encode all the values without any exceptions. But most values do not need 10 bits, so a bit width of 5 would be more efficient, but requires storing one exception. Encoding at bit width 4 requires 2 exceptions, and so on. The function above is intentionally kept simple for illustration. We can make it faster by moving the per-bit-width loop outside the per-element loop . The fast version still needs about 12 instructions per value. With SIMD, we can reduce this to by 8x to only 1.5 instructions per value! The trick is to turn each input value into its “smear mask” (imagine taking the first 1 bit and smearing it across the remaining positions). Here are the smear masks for our example: Turning a value into its smear mask is computationally cheap: Go implements (functions like ) by calculating . We can calculate the “smear mask” of a value with , i.e. starting with a 32-one-bits mask and shifting it by the number of leading zeros. Now, to obtain e.g. , we can count the 1 bits at bit position 4 of all input values. The instruction counts bits very efficiently, but it counts one bits within a register, so it counts rows, not columns. Counting columns is called Positional Population Count . I found the following papers that describe positional popcount with SIMD: To understand the AVX512 implementation of positional popcount, I found it most helpful to visualize an AVX512 register (512 bits, i.e. 64 bytes). The graphic below uses the layout, meaning it divides the register into 8 lanes of 64 bits (= 8 bytes) each. This illustration shows the whole process: how s are loaded into an AVX512 register (all 4 of its bytes, in sequence) and where we end up, i.e. the 32 positional popcounts: Let’s break down this process into its individual steps. First, we turn each loaded value into its smear mask as explained above. The vector instruction calculates (1 byte) of 64 bytes at once, but first we need to shuffle the bytes inside the register: in load order, we have a full (4 bytes), followed by another , per lane. First, we permute the bytes ( ) such that all the first bytes of each value end up in one lane (“transpose the bytes”): Next, we “transpose the bits” using the instruction, which sounds scary but turns out to be quite flexible for bit manipulation of all kinds. The instruction is also “the star of the show” in Go’s Green Tea Garbage Collector (2025). Here is the bit transpose, shown in the AVX512 register layout (see below for a different layout): I found it easier to understand the transpose step when arranging the 8 bytes of lane 0 from top-to-bottom (instead of left-to-right), because then it looks like a 90 degree clockwise rotation: Now we can use to count the bits in all 64 bytes at once: After all loop iterations (processing 16 values each) are done, we add the two groups (first 8 values, second 8 values) to obtain the 32 exception counts: Here is the Go code that implements what I described visually above: Have a look at the commit introducing positional popcount to DCS for the full code (including shuffle tables and ISA checks) as well as the detailed benchmark results. The SIMD optimizations I showed above beat the cgo TurboPFor library that Debian Code Search used before. When comparing apples to apples, i.e. backporting the AVX512 kernels and positional popcount technique to C TurboPFor, Go benchmarks a little slower at ≈1.4x C. Could we make my Go TurboPFor implementation even faster, to truly match the C speed? Yes! But also no. Let me explain: We could use more SIMD instructions to remove all code that still processes one value at a time. For example, in my encoder’s function. Or we could price all bit widths concurrently in . Or in the decoder’s exception apply code path. But all of these SIMD instructions make understanding (and changing) the code harder, so I am cautious regarding which ones I introduce. A big part of the performance gap is due to Go’s bounds checks . While it costs performance, bounds checking is great for safety, so I will not turn off bounds checking. The Go compiler eliminates a number of bounds checks when it understands it’s safe to do so. One optimization avenue could be to make the prove pass in the Go compiler smarter to eliminate more bounds checks. When doing mid-stack inlining (proposal #19348) (2017), Go sometimes needs to put instructions into the binary so that it can attach inlining markers. For dispatch-bound functions, these extra NOPs can measurable slow down execution. The Go compiler currently allows specifying the architecture ( ) and microarchitecture ( ), but not a specific CPU architecture (like AMD Zen 4). Therefore, CPU-specific workarounds for one vendor affect all the generated code. The specific one I encountered in my code is that the Go compiler emits before every to break a false-output-dependency from the Intel Sandy Bridge Skylake era, which is unnecessary on AMD Zen CPUs. I suspect that Go intentionally does not offer this level of customizability. After all of the above points are addressed, what remains is better code generation in specific cases. To illustrate what I mean, consider the example of incrementing a loop variable, where Go re-derives an index every time: Go: (3 instructions) clang: (2 instructions) Depending on the specific case, improving the compiler might be easy or prohibitively complex. Often, such improvements are hard to measure conclusively. Go’s SIMD support makes available — in Go code without having to resort to cgo or assembly — a powerful part of modern CPUs which allows speeding up the kind of computation that TurboPFor needs by an order of magnitude! 😲 I found it very valuable to use a coding agent (Claude Code, with Opus 5 and Fable 5 in this case) to help with the many tedious parts of such performance work (and still it took me weeks!). The LLM can read objdump output much faster than I can, can see patterns and correlations I might never identify, never becomes frustrated after a compiler error or runtime panic, and never runs out of patience to run one more experiment, as long as I give it measurable and reachable goals. The performance of the SIMD code which one can get from the Go compiler is pretty close to what a good C compiler like clang provides. The CPU performance counters show value decoding speeds of 7 instructions/cycle (IPC) on a machine where the maximum is 8 IPC. To me, SIMD support is a very welcome addition to Go. Hand-writing Go assembler code . This is only doable for small functions, for example is implemented with hand-written Go assembly (including AVX2). Generating Go assembler code with tools like Michael McLoughlin’s “Avo” . This is how uses AVX2 . While Avo generator code definitely is higher-level than hind-written assembly, it is still too close to assembly for my taste. Use a C library via cgo so gcc or clang compiles SIMD code. Debian Code Search used to use the powturbo/TurboPFor C library via cgo for the last 7 years. Partial Indexing: When a new package (or package version) enters Debian, all of its (text) files are indexed. If the package (hypothetically) contained only with , we would assign document ID to and store in the partial index that trigrams , , , , etc. are all found in doc ( ). Full Index Merging: The many thousands of partial index files (for each Debian package) are combined into a small handful of large index files: When searching, it would be expensive to consult thousands of indexes. To merge multiple partial index files into one larger index (which can then be efficiently queried), we need to re-encode the partial index files: what used to be document ID in the partial index might be document ID in the full index. Querying (searching): When users enter search queries, these queries need to be answered as quickly as possible. The relevant entries in the full indexes are decoded (in parallel). The TurboPFor bitpacking block type ( bitpacking implementation commit ) encodes a bit stream of variable bit width (where the bit width is in range ) in little endian byte order. By scanning all values and choosing the smallest bit width that allows representing all values, this technique saves disk space (compresses). The bitpacking with exceptions block type ( bitpacking with exceptions implementation commit ) determines two bit widths: one for values, the other bit width for encoding exceptions. This allows choosing a lower bit width (that does not cover all values) compared to the bitpacking block type. A bitmap encodes whether a value has an exception or not. The bitpacking with VB exceptions block type ( bitpacking with VB exceptions implementation commit ) is a variant which does not use an exception bitmap and encodes exceptions using a variable byte integer encoding. This is more efficient when there are few exceptions (less than 20) or the exceptions are very different in bit width compared to the other values. Lastly, the constant block type ( constant implementation commit ) stores just one value on disk. This is useful for all-zero or all-one blocks, for example. The number of input values ( ), but not their actual value. The bit width to pack into ( ). Bitpack full blocks with SIMD (AVX2) Gather exceptions using SIMD (AVX512) Use generics to specialize per bit width 2019: “Efficient Computation of Positional Population Counts Using SIMD Instructions” (Klarqvist, Muła, Lemire) introduces an AVX512 implementation using Carry-Save Adder (CSA) networks, but in my testing, that approach is slower for TurboPFor encoding. 2024: “Histogramming bytes with positional popcount (GF2P8AFFINEQB edition)” (Harold Aptroot) shared a C++ implementation illustrating the technique I am using. If you are not familiar with how C++ vector intrinsics look, take a look at this example. 2025: “Faster Positional-Population Counts for AVX2, AVX-512, and ASIMD” (Clausecker, Lemire, Schintke) improves performance over the 2019 paper, but cites the Aptroot blog post as “Future Work”, promising even faster processing for smaller inputs. We could use more SIMD instructions to remove all code that still processes one value at a time. For example, in my encoder’s function. Or we could price all bit widths concurrently in . Or in the decoder’s exception apply code path. But all of these SIMD instructions make understanding (and changing) the code harder, so I am cautious regarding which ones I introduce. A big part of the performance gap is due to Go’s bounds checks . While it costs performance, bounds checking is great for safety, so I will not turn off bounds checking. The Go compiler eliminates a number of bounds checks when it understands it’s safe to do so. One optimization avenue could be to make the prove pass in the Go compiler smarter to eliminate more bounds checks. When doing mid-stack inlining (proposal #19348) (2017), Go sometimes needs to put instructions into the binary so that it can attach inlining markers. For dispatch-bound functions, these extra NOPs can measurable slow down execution. The Go compiler currently allows specifying the architecture ( ) and microarchitecture ( ), but not a specific CPU architecture (like AMD Zen 4). Therefore, CPU-specific workarounds for one vendor affect all the generated code. The specific one I encountered in my code is that the Go compiler emits before every to break a false-output-dependency from the Intel Sandy Bridge Skylake era, which is unnecessary on AMD Zen CPUs. I suspect that Go intentionally does not offer this level of customizability. After all of the above points are addressed, what remains is better code generation in specific cases. To illustrate what I mean, consider the example of incrementing a loop variable, where Go re-derives an index every time: Go: (3 instructions) clang: (2 instructions) Depending on the specific case, improving the compiler might be easy or prohibitively complex. Often, such improvements are hard to measure conclusively.

0 views