Latest Posts (20 found)

Remote EngFlow caching meets an old G4

During BazelCon 2026 in early October, the fine folks at EngFlow gave me a very cool piece of swag: a Cache & Carry box or, in other words, a portable remote cache for Bazel builds. The only ask was for me to post a photo on social media, which I’d have gladly done, but… that seemed like too low a price for a nice piece of hardware. So I promised I would write an article instead. The article is late, though, as I have been busy getting ZKeys out the door and trying to find a good idea for what to talk about. I finally got the right inspiration after taking an old PowerBook G4 laptop from 2004 out of the closet to play with Tabby-PPC . That experiment failed, but as the laptop sat on my desk, I thought: could I make it leverage the Cache & Carry and demonstrate the clear benefits of remote caching? The answer was “of course yes” before even trying, but it was not going to be easy: this machine is severely underpowered by today’s standards and won’t run Bazel, so showing remote caching via a modern build system wasn’t going to be possible. I had to find an alternative demonstration path, and find it I did: the recc compiler wrapper . Even then, the benefits weren’t great on the first try, so I had to debug and iterate. In the end, the compilation time for itself dropped from a little over 1 hour to just 3 minutes. Let’s see how. Typing articles like this one, with manually-taken pictures and hand-edited videos, requires a lot of work. Subscribe to Blog System/5 to show your support. EngFlow is a relatively new company that offers a hosted remote caching and execution service for Bazel builds. More specifically, EngFlow is an implementation of the Remote Execution (RE) API . And fun fact: the protocol name is RE, not RBE as many people call it, because RBE was Google’s own RE service that never really saw the light of day. The EngFlow Cache & Carry in its box before unpacking it. Cache & Carry is a little toy that packages the EngFlow remote cache (not execution) software into a Raspberry Pi 4 preconfigured to work as an appliance, enclosed into a branded 3D-printed case and packaged into a fancy cardboard box. Mind you: this is what I wanted to achieve with my own EndBOX last year but never went the last mile to distribute it as a truly finished toy. The EngFlow Cache & Carry Raspberry Pi 4, with its custom branded case. Getting started I’m quite used to EngFlow’s product by now because we use it at Snowflake to power our in-house builds and tests, so using the Cache & Carry was no difficulty. And it shouldn’t be for anyone given that configuration and management are pretty easy. Here is the cluster status page right after plugging in the device and connecting to it, showing how this “cluster” is really just a cache and has no remote execution features: EngFlow's standard Cluster status page in the live dashboard. Using it to run Bazel builds is trivial, really. All it took was to stick these few lines in my file, as the instructions say: And just like that, builds started showing up in the UI: EngFlow's standard Invocations browser in the live dashboard. This is one of the weakest parts of the UI, to be honest, because of its poor search capabilities, but the team is hard at work redesigning it. We can even peek into one of the builds to observe cache statistics: EngFlow's Invocation Details drill-down view in the dashboard. Here we can see the cache usage status and that the whole build was cached and took only 17 seconds to run (compared to the 13 minutes it takes otherwise). One thing that did surprise me about this setup is the ability to carry power and Ethernet over a single USB-C cable between the Raspberry Pi 4 and the host. I didn’t know this was possible, and it’s a great feature: if you just want to use the Cache & Carry with your laptop, all you have to do is plug it in with one cable and it just works. Getting Bazel to work against EngFlow was easy. But… as I told you earlier, EngFlow is not just a remote caching and execution service for Bazel: it is an implementation of the RE API. With some imagination, you would think that there might be clients other than Bazel for this API, and you would be right. Buck 2—Meta’s build system—is an obvious example, but there are more niche clients. And the one I discovered while searching whether supported EngFlow and finding that it didn’t was : a compiler wrapper like and that uses RE for caching and remote execution. Building and installing is easy: But note I installed the binary as , not . The rationale for this is that we have to configure . This is done via environment variables, and as I don’t like to pollute my regular environment with program-specific noise, I created a launcher like the following: With this in place, we can run a single compilation command and verify that the wrapper runs: And, with a repeated invocation, we can ensure that caching is in effect: OK, time to pick up the PowerBook G4 from 2004. This little 12” laptop sports a PowerPC G4 (7447A) running at a whopping 1.5 GHz, with 768 MB of RAM, a super-duper-slow 80 GB spinning drive, and a 100 Mbit Ethernet link. Not a lot, you’d say… but this computer was frigging amazing back in the day. I had the iBook G4 back in the day and was always jealous of the PowerBooks I saw in the wild, unaffordable to me, so when I could grab this one for $40 a few years ago, I just had to. EngFlow Cache & Carry in its box next to the PowerBook G4 12” from 2004 we’ll use as a client. Right now, this machine is running Debian forky/sid, one of the only Linux distros out there that still works out of the box on 32-bit PowerPC. As of 2026-11-09, it reports: With the specs out of the way, let’s go back to the premise of the article: showing you what a massive and unsurprising difference (remote) caching can make during compilations, and how, because RE is “just a protocol”, we can leverage it even from old machines. For this, we’ll measure ’s own build from a clean slate, cached and uncached, because it’s a large enough C++ project that takes about an hour to build out of the box—not too little, but also not so much as to be discouraging. Here are the final numbers of the comparison: Let’s break them down. My first attempt at using remote caching was to build with itself in the “default” configuration for and the toolchain installed by Debian. This meant GCC 16.2 and no custom flags to CMake. The clean, fully-cached build took about 8 minutes to finish. This showed a nice ~7x speedup compared to the clean unwrapped build, but somehow it felt like not enough. Why did we still spend 8 minutes to compile something when everything should be cached? I had two theories, but neither of them was valid: The machine doesn’t have a lot of RAM for C++ compiles. Was causing it to thrash, maybe because it buffers files in memory instead of transferring them in chunks? Looking at the code, the answer was no: implements chunked uploads and downloads. The machine’s Ethernet port is slow. Were network transfers slowing things down? Not really either: the output tree is only ~150MB after a build. (Mind you, with Bazel and remote execution, you’d typically use to avoid ferrying large intermediate object files, but that’s not an option with a compiler wrapper that knows nothing about the end-to-end build graph.) With both theories debunked, I had to look elsewhere: CPU consumption. It is no surprise that compiler wrappers are compute-heavy. One specific CPU-bound operation for C++ wrappers is dependency scanning: these wrappers have to (re)discover on their own what a specific compilation action depends on, because nothing tells them upfront. When the wrapper sees something like , it can tell that depends on … but what about the thousands of other implied dependencies like header files and toolchain binaries involved in that innocent invocation? You must know what those are in order to generate a cache key that can disambiguate different environments correctly. Taking some measurements, dependency scanning was indeed the problem as more than 5 out of the total 8 minutes of the cached build were spent on it. Looking through the codebase, I found that implements support for : a helper tool that ships with Clang and is specifically designed to speed up dependency discovery. Would it help here? I switched to Clang, reran the build and… whoops, still no bueno. The unwrapped build was, interestingly, much faster than the GCC one, but did not help: the logs claimed that it succeeded only for 23 out of 124 scanner runs, and so it didn’t materially change the overall result. Looking further, I found that was not being effective: ’s scanner adds to the compile commands, and because precompiled headers (PCHs) had been built without that option, Clang rejected using it. So… what if we disable PCHs by adding to the CMake invocation? Well, it turns out this made no difference either because CMake emits in this case, and apparently probes for these flags wrong, which in turn causes to fall back to slow dependency scanning. I applied a very hacky, targeted fix to to ensure was effective, reran the measurements, and got these numbers. Focus on the PCH? and Dep scanning columns: Yay! End-to-end clean, fully-cached build times fell from 8 minutes to 3 minutes, and those 3 minutes are pretty much the cost of the entire build and account for local non-compiler work such as protobuf generation and linking. Still not zero, but much better than what we started with. Here is the 1-minute video comparing build times. The difference is pretty massive: Recording of recc's own compilation on a PowerBook G4 without and with remote caching. As you can see, there is nothing magical about remote caching, and EngFlow’s Cache & Carry is a little toy to play with this technology. You can, of course, download an open source alternative such as Builbarn , but playing with a preconfigured appliance was fun and removed a lot of the complexities of setting such a system up. When paired with a modern build system such as Bazel, remote caching (and execution) can be trivially enabled and can achieve near 0-second build times when the whole build is cached: these build systems have precise knowledge of the full build graph and know which paths in it are or are not invalidated for a given build. And because they have this knowledge, they can apply optimizations to the whole build such as not downloading intermediate artifacts. But as we have seen, RE is just a protocol, and if you can speak it, you can leverage it from pretty much any machine (even if ancient and “worthless”) and any build system. You’ll hit some inherent limitations, like a compiler wrapper having only a very narrow view of the build, or you’ll have to deal with strange corner cases that don’t allow maximum efficiency, but you can make it work. Keep caching and carrying! The EngFlow Cache & Carry in its box before unpacking it. Cache & Carry is a little toy that packages the EngFlow remote cache (not execution) software into a Raspberry Pi 4 preconfigured to work as an appliance, enclosed into a branded 3D-printed case and packaged into a fancy cardboard box. Mind you: this is what I wanted to achieve with my own EndBOX last year but never went the last mile to distribute it as a truly finished toy. The EngFlow Cache & Carry Raspberry Pi 4, with its custom branded case. Getting started I’m quite used to EngFlow’s product by now because we use it at Snowflake to power our in-house builds and tests, so using the Cache & Carry was no difficulty. And it shouldn’t be for anyone given that configuration and management are pretty easy. Here is the cluster status page right after plugging in the device and connecting to it, showing how this “cluster” is really just a cache and has no remote execution features: EngFlow's standard Cluster status page in the live dashboard. Using it to run Bazel builds is trivial, really. All it took was to stick these few lines in my file, as the instructions say: And just like that, builds started showing up in the UI: EngFlow's standard Invocations browser in the live dashboard. This is one of the weakest parts of the UI, to be honest, because of its poor search capabilities, but the team is hard at work redesigning it. We can even peek into one of the builds to observe cache statistics: EngFlow's Invocation Details drill-down view in the dashboard. Here we can see the cache usage status and that the whole build was cached and took only 17 seconds to run (compared to the 13 minutes it takes otherwise). One thing that did surprise me about this setup is the ability to carry power and Ethernet over a single USB-C cable between the Raspberry Pi 4 and the host. I didn’t know this was possible, and it’s a great feature: if you just want to use the Cache & Carry with your laptop, all you have to do is plug it in with one cable and it just works. Bypassing Bazel Getting Bazel to work against EngFlow was easy. But… as I told you earlier, EngFlow is not just a remote caching and execution service for Bazel: it is an implementation of the RE API. With some imagination, you would think that there might be clients other than Bazel for this API, and you would be right. Buck 2—Meta’s build system—is an obvious example, but there are more niche clients. And the one I discovered while searching whether supported EngFlow and finding that it didn’t was : a compiler wrapper like and that uses RE for caching and remote execution. Building and installing is easy: But note I installed the binary as , not . The rationale for this is that we have to configure . This is done via environment variables, and as I don’t like to pollute my regular environment with program-specific noise, I created a launcher like the following: With this in place, we can run a single compilation command and verify that the wrapper runs: And, with a repeated invocation, we can ensure that caching is in effect: Let’s go retro OK, time to pick up the PowerBook G4 from 2004. This little 12” laptop sports a PowerPC G4 (7447A) running at a whopping 1.5 GHz, with 768 MB of RAM, a super-duper-slow 80 GB spinning drive, and a 100 Mbit Ethernet link. Not a lot, you’d say… but this computer was frigging amazing back in the day. I had the iBook G4 back in the day and was always jealous of the PowerBooks I saw in the wild, unaffordable to me, so when I could grab this one for $40 a few years ago, I just had to. EngFlow Cache & Carry in its box next to the PowerBook G4 12” from 2004 we’ll use as a client. Right now, this machine is running Debian forky/sid, one of the only Linux distros out there that still works out of the box on 32-bit PowerPC. As of 2026-11-09, it reports: With the specs out of the way, let’s go back to the premise of the article: showing you what a massive and unsurprising difference (remote) caching can make during compilations, and how, because RE is “just a protocol”, we can leverage it even from old machines. For this, we’ll measure ’s own build from a clean slate, cached and uncached, because it’s a large enough C++ project that takes about an hour to build out of the box—not too little, but also not so much as to be discouraging. Here are the final numbers of the comparison: Let’s break them down. First build, slow My first attempt at using remote caching was to build with itself in the “default” configuration for and the toolchain installed by Debian. This meant GCC 16.2 and no custom flags to CMake. The clean, fully-cached build took about 8 minutes to finish. This showed a nice ~7x speedup compared to the clean unwrapped build, but somehow it felt like not enough. Why did we still spend 8 minutes to compile something when everything should be cached? I had two theories, but neither of them was valid: The machine doesn’t have a lot of RAM for C++ compiles. Was causing it to thrash, maybe because it buffers files in memory instead of transferring them in chunks? Looking at the code, the answer was no: implements chunked uploads and downloads. The machine’s Ethernet port is slow. Were network transfers slowing things down? Not really either: the output tree is only ~150MB after a build. (Mind you, with Bazel and remote execution, you’d typically use to avoid ferrying large intermediate object files, but that’s not an option with a compiler wrapper that knows nothing about the end-to-end build graph.)

0 views
Blog System/5 1 weeks ago

Unattended reboots with encrypted disks

Do you run a small home server or NAS holding your precious photos and sensitive documents? If so, I suppose the drives are encrypted, right? But then… can you reboot the machine without manually entering a passphrase before being able to access your files again? If you answered yes to the questions above—which is common for convenience—that implies the encryption keys live in the machine which… kinda defeats the purpose of disk encryption, doesn’t it? A thief can break into your house, lift the whole box (they are small these days, huh), plug it in elsewhere, and gain free rein over your files. So, which one is it? Simplicity and reliability by allowing automatic reboots or data protection by keeping the key in your head? With ZKeys—a little new project I’m launching today—you can have your cake and eat it too. TL;DR ZKeys is a managed service that stores encryption passphrases off-site. Client machines fetch the encryption keys from the service and keep those keys alive (unlocked) via periodic keepalive messages. If the server stops receiving those messages for a long period of time (e.g. because it has been unplugged as part of theft), access to the key is automatically locked. You get automatic, passwordless reboots while keeping your data protected against real incidents. Did you know that, by subscribing to Blog System/5, you support the creation of this content and this software? About a year ago, I was reinstalling my FreeBSD home server to act as my NAS after a short stint with a Synology box . During that process, I decided to enable encryption for the ZFS data pool. But as I did that, I faced the question: how do I allow the machine to automatically serve my data after a reboot? I could put the key in a local file, which FreeBSD supports via the ZFS option, but that would render disk encryption pretty much useless. So I had an idea: what if I put the key on a different machine away from my house? I could then make the NAS fetch the key to mount the drives. And if someone stole the server, I could wipe the remote key and make the data unreadable before they could plug it back in. I did post this to Twitter and there was some interest in the idea: But… did you notice the problem with what I said above? Wiping the key by hand after noticing something is wrong is problematic because the gap between those two events may be large. What if I’m on a long vacation and I have no means of noticing that the machine has been stolen? Game over. So I refined the idea: what if I had a service that stored the key remotely and required the consuming machine to send it frequent pings to keep the key unlocked? This way, if the machine were stolen, it’d likely be offline for more than a few minutes and the service could automatically determine that something is wrong and lock the key from future accesses. And that’s precisely what ZKeys does. Before getting into details, it’s important to get something out of the way early on: ZKeys is designed so that a compromise of the server is insufficient to retrieve or reconstruct your keys. This is done in two ways: Split keys: The ZKeys server only stores half of the passphrase used to unlock a volume. The other half remains on the client machine. The client program combines both halves to produce the whole passphrase. Encryption at rest: The keys are encrypted at rest with a password that the client must supply for retrieval and which is securely transmitted over HTTPS. The password only lives in the server’s memory for a brief period of time. The tradeoff is, simply, that you MUST back up the full encryption keys in a third location of your own (a paper in a safe, a password manager, you name it). If ZKeys goes down or you lose your remote key password, there is absolutely nothing I can do to help you. You have been warned. The setup instructions later on will instruct you how to back the key up. The ZKeys service is available at https://zkeys.jmmv.dev/ and the open-source client—along with system integrations for FreeBSD and Fedora—is in my jmmv/zkeys repository. Disclaimer: ZKeys is offered to you for free. I make no promises about its reliability, availability, or anything else. I am giving you access because I expect that supporting a handful of extra users won’t be a big issue. But if support becomes a burden, or if load becomes unmanageable, I’ll have to re-evaluate my choices here. Which means that, for now, you have to use the limited code to get started! The basic idea to set ZKeys up is the following: Install the client CLI tool. Create a service account. Create a new key (or onboard an existing key). Configure the keep-alive service on the target machine. Change or add the filesystem encryption key to be the one stored in ZKeys. Configure the auto-mount service on the target machine. That’s all it takes, but the steps are quite manual at the moment because no upstream OSes provide packages. The service documentation covers several scenarios in detail for FreeBSD and Fedora, so I’m not going to repeat them here. Demo of the integration between ZKeys and Fedora 44 with a fully encrypted root volume: the video starts by showing a fully unattended boot, followed by a manual lock of a key that causes Fedora to refuse to reboot on its own, and finishes with another automatic reboot after the key has been unlocked again. Now for the nerdy details, because that’s what you’re here for: The CLI is Rust, of course, but it has to come with a bunch of shell scripts to integrate with FreeBSD’s rc.d system and Fedora’s systemd and dracut. These integration points are the trickiest part of the client package and the hardest to validate automatically, which is why I only provide support for the two systems I use on a daily basis. It should be possible to integrate ZKeys with any other Unix-like OS, though. The CLI package is a frankenmonster made up of Cargo and GNU Automake/Autoconf because of the above. I believe system-level tools should abide by de facto standard tooling even if such standard tooling is deficient, so GNU Autotools it is. I run two non-replicated instances of the service: one in US West and one in EU West, because I have machines in both locations and both rely on encryption. I strongly suggest you use the US instance as I’m seeing frequent power hiccups in my EU deployment. The frontend uses Bootstrap, straight from the 2010s. Does it look ugly? Maybe, but I kinda like it and, most importantly, it’s functional . Of course I could have asked AI to produce yet-another-dull-site full of gradients and slop, but I did not want to do that, so I stuck to what I already knew how to do by hand from previous services. The admin page is an SPA, yes. This is an intentional design choice that forces a very clear separation between the backend APIs and the frontend. Whatever the current web frontend can do any other client can do as well. For example: the current CLI tool does not offer administrative operations but it could trivially be made to support them, because the APIs are right there. The backend is built on my own III-IV framework which I’ve been building up over the last few years while implementing a couple of other services. I’ve had to add a lot more features to it to make this possible though. Oops, I know that’s the name of a different effort , but you really need to encrypt your local drives. With computers becoming smaller and lighter every day, it’s easier than ever to steal them, and unfortunately home break-ins are common in some parts of the world. Block-level encryption is cheap in CPU terms, so do it. ZKeys just makes this process less cumbersome for headless servers. Once again, head to: https://zkeys.jmmv.dev/ to get started and use code to create an account! And if you are interested in helping out, I’d appreciate the creation of packages for FreeBSD and Fedora, and integration scripts for other systems. TL;DR ZKeys is a managed service that stores encryption passphrases off-site. Client machines fetch the encryption keys from the service and keep those keys alive (unlocked) via periodic keepalive messages. If the server stops receiving those messages for a long period of time (e.g. because it has been unplugged as part of theft), access to the key is automatically locked. You get automatic, passwordless reboots while keeping your data protected against real incidents. Did you know that, by subscribing to Blog System/5, you support the creation of this content and this software? Storytime About a year ago, I was reinstalling my FreeBSD home server to act as my NAS after a short stint with a Synology box . During that process, I decided to enable encryption for the ZFS data pool. But as I did that, I faced the question: how do I allow the machine to automatically serve my data after a reboot? I could put the key in a local file, which FreeBSD supports via the ZFS option, but that would render disk encryption pretty much useless. So I had an idea: what if I put the key on a different machine away from my house? I could then make the NAS fetch the key to mount the drives. And if someone stole the server, I could wipe the remote key and make the data unreadable before they could plug it back in. I did post this to Twitter and there was some interest in the idea: But… did you notice the problem with what I said above? Wiping the key by hand after noticing something is wrong is problematic because the gap between those two events may be large. What if I’m on a long vacation and I have no means of noticing that the machine has been stolen? Game over. So I refined the idea: what if I had a service that stored the key remotely and required the consuming machine to send it frequent pings to keep the key unlocked? This way, if the machine were stolen, it’d likely be offline for more than a few minutes and the service could automatically determine that something is wrong and lock the key from future accesses. And that’s precisely what ZKeys does. Zero-knowledge protection Before getting into details, it’s important to get something out of the way early on: ZKeys is designed so that a compromise of the server is insufficient to retrieve or reconstruct your keys. This is done in two ways: Split keys: The ZKeys server only stores half of the passphrase used to unlock a volume. The other half remains on the client machine. The client program combines both halves to produce the whole passphrase. Encryption at rest: The keys are encrypted at rest with a password that the client must supply for retrieval and which is securely transmitted over HTTPS. The password only lives in the server’s memory for a brief period of time. Install the client CLI tool. Create a service account. Create a new key (or onboard an existing key). Configure the keep-alive service on the target machine. Change or add the filesystem encryption key to be the one stored in ZKeys. Configure the auto-mount service on the target machine. The CLI is Rust, of course, but it has to come with a bunch of shell scripts to integrate with FreeBSD’s rc.d system and Fedora’s systemd and dracut. These integration points are the trickiest part of the client package and the hardest to validate automatically, which is why I only provide support for the two systems I use on a daily basis. It should be possible to integrate ZKeys with any other Unix-like OS, though. The CLI package is a frankenmonster made up of Cargo and GNU Automake/Autoconf because of the above. I believe system-level tools should abide by de facto standard tooling even if such standard tooling is deficient, so GNU Autotools it is. I run two non-replicated instances of the service: one in US West and one in EU West, because I have machines in both locations and both rely on encryption. I strongly suggest you use the US instance as I’m seeing frequent power hiccups in my EU deployment. The frontend uses Bootstrap, straight from the 2010s. Does it look ugly? Maybe, but I kinda like it and, most importantly, it’s functional . Of course I could have asked AI to produce yet-another-dull-site full of gradients and slop, but I did not want to do that, so I stuck to what I already knew how to do by hand from previous services. The admin page is an SPA, yes. This is an intentional design choice that forces a very clear separation between the backend APIs and the frontend. Whatever the current web frontend can do any other client can do as well. For example: the current CLI tool does not offer administrative operations but it could trivially be made to support them, because the APIs are right there. The backend is built on my own III-IV framework which I’ve been building up over the last few years while implementing a couple of other services. I’ve had to add a lot more features to it to make this possible though.

0 views
Blog System/5 3 weeks ago

BazelCon 2026 recap

We are right in the middle of fall, and that means BazelCon 2026 just took place. This time around it was hosted in Amsterdam and spanned three days: one day of tutorials and an overlapping Buildbarn meetup that I wasn’t aware of, and two days of main-conference talks and events. And as the event is behind us, it’s time for the now-traditional recap. Welcome to BazelCon 2026 sign. What follows is a recollection of my notes arranged by topic and intermixed with my own commentary and thoughts. Some sections and topics are more detailed than others because in some cases I didn’t have a seat and couldn’t type enough, and in others I got distracted in the hallways chatting with people. Speaking of people, several of you approached me to praise previous editions of these recaps, so I now feel obliged to write another one. Thanks for the kind comments! As we will see, “scale” was a central theme of the conference: AI is multiplying concurrent builds and tests, artifacts and graphs are growing at an accelerated pace due to new features like configuration transitions, and the ecosystem is responding by making execution, caching, and analysis more efficient. There is a lot to cover but here are a few things that felt memorable to me : The BUILD Foundation is now a reality, giving the Bazel ecosystem a vendor-neutral home. Its goal is to act as a proxy between the community and Google to help Google understand what to prioritize and to fund projects. If your company can spare “a few” dollars, please donate! AI-driven development is having a broad impact on the industry and, in particular, everyone is seeing their CI systems become overloaded. Well, news at 11: I’m dealing with this day in and day out. But what was new to me was that we at Snowflake are not the only ones struggling with local system overload. Lots of people out there have likewise “discovered” Git worktrees as a way to run multiple agents in parallel, which in turn means multiple concurrent Bazel servers. Bazel 10 is shaping up to be a substantial release that will help with the problem right above due to its many performance improvements and memory consumption optimizations. Have you struggled to keep Bazel up-to-date before? These days, if you want to get any platform-related work funded you have to spin it in terms of AI, so this release will be an easy sell. Let’s “Rewrite it in Rust”? I’m impressed. Google is seriously evaluating a progressive rewrite of Bazel in Rust, and this is probably the most exciting news I got out of the conference. You know I’ve been critical of Bazel’s usage of Java since day one so, if this takes off, I’ll be the first in line to evaluate the results (and it will likely push me to actually contribute to Bazel again). Fast and correct sandboxing on macOS remains a problem. This is “interesting” to me because it’s a problem I tried to fix almost ten years ago with the original sandboxfs, but I failed because of unexpected bugs in macOS’s FUSE support and eventually abandoned the idea when FUSE became a dead end on Apple’s platforms. Funnily enough, other folks have now reinvented sandboxfs—and even given it the same name (ugh)—and there is even another implementation of a similar idea in the form of actiondFS. Types are coming to Starlark, but Bazel’s late arrival to the party means that multiple competing approaches now exist. We have at least two LSPs with different annotation mechanisms and Buck 2’s own syntax. Hopefully they can all converge. Platforms and configurations remain difficult to model at scale. Careless use of transitions and build settings can produce an explosion of configured actions. Apparently, as one speaker noted, AI agents love transitions for some reason, which is interesting because they are not a popular feature and they are not particularly easy to use. Let’s dive into the full report now. You’ll find my notes arranged by talk but I’ve tried to group them into higher-level themes for easier navigation. These conference summaries take effort to write, and some of you are waiting for them. Show your true support by subscribing! The two keynotes are usually the most information-packed events but… as you can imagine they are also the most popular. The venue this year was not roomy enough to host BazelCon’s attendance (Helen quoted that we got 600 registrations), so I had to stand for these two events. The recordings and slides are not out yet, so consequently, I can only tell you a few details from memory. The conference opened with the usual Bazel Community Update , presented by Helen Altshuler from EngFlow and Chuck Grindel from Glydways. The biggest announcement is that the BUILD Foundation is now a reality. The effort had been discussed at the previous two BazelCons and likely various meetups, but it had remained mostly invisible while its organizers worked through the legal and financial details. The foundation now provides a neutral organization to support the broader build ecosystem (in their words this is not just for Bazel), and it is looking for both members and concrete proposals to fund. If you want to get involved, get your company pumped up and email [email protected] . Documentation continues to receive attention as it has always been a lowlight in previous surveys. Work is underway to make the docs easier for the community to own and improve by decoupling them from Google’s internal systems. But one must wonder: what exactly is the biggest problem with documentation in today’s world? AI agents used to do terribly with Bazel just a year ago and nowadays do… fine as we shall see in the summary. Maybe the work on documentation needs a different spin now. And as usual, a reminder to fill the annual Bazel user survey . Your input is necessary to quantify ecosystem-wide pain points and influence future work, especially now that the foundation exists. John Field and Tobias Werth from Google followed with the State of the Union , which presents a recap of major improvements during the year and the path ahead for Bazel 10 and beyond. Performance remains a major theme. Google reported improvements of about 15% in some workloads together with reductions in memory consumption. Some of these speedups come from upgrading from Java 25 to 27, while others come from correct action rewinding, optimizations to Skyframe cache pruning, and content-defined chunking. These changes are very relevant because Bazel’s large memory consumption gets in the way of scaling CI and prevents using multiple AI agents in parallel. And here is where we heard about Skymetal: the codename for the Google-internal exploration of rewriting Bazel in Rust. The rationale for this rewrite is obviously performance, and I’m guessing it’s now a real consideration because AI can make such large-scale changes feasible. Tobias acknowledged that Java was a reasonable choice back in 2006 when Blaze started and that the JVM can deliver great throughput performance at scale… but it is not the best choice for a tool like Bazel in this day and age, especially when optimizing for memory efficiency is critical. I called it in 2015. I have been in the BazelCon Program Committee (PC) for 3 years now. I remember that, during last year’s review, we encountered a few AI talks but I think none made the cut: they all looked too hype-y and out of place. But it was impossible to ignore the topic this year, and it was actually important to bring AI-related talks on board to not sound tone deaf. AI is a reality in our industry, and Bazel is a key component to survive the transition. Nicolas Lopez from EngFlow and I, representing Snowflake, presented AI Development: Challenges and Early Learnings for Bazel . Agentic workflows have expanded rapidly throughout 2026, and the effects are visible well beyond code generation. At Snowflake, we were fortunate enough to finish our Bazel migration and to stabilize remote execution by moving from our self-hosted open-source deployment to EngFlow’s fully-managed service before all of this happened. And I say fortunate because the increase in CI load that AI workflows brings can only be handled with a good build system and caching story. But none of that is news, so the core of the talk was to look at how Bazel usage looks different in agent-initiated environments. The key points from my side: Agents run more builds more frequently than humans, discover and invoke targets that were often “internal only”, and explore several approaches in parallel. Your intuition about how to evaluate which builds matter and how to measure them is probably wrong by now. Bazel and IDEs have never played great together and maybe that just doesn’t matter anymore. We are seeing a sharp decline in IDE usage, although developers still want a way to browse code changes and debug them. This means LSPs are key now to support “leaner” IDEs, and maybe standalone debuggers. Short build and test latency is critical when a human must remain focused on a coding task but, in an agentic workflow, the constraints are different. You know that, after you hit “execute this plan”, the agent will take many minutes to return so minimal build latency is not as important. And actually… maybe you now want to trade some latency in exchange for extra validations so that agents have to take fewer turns to converge. And because humans are now waiting for agents to finish for long periods of time, they have to fill that time with other tasks, which has driven them to adopt Git worktrees en masse. This is leading to scalability problems on dev machines because multiple concurrent Bazel server processes are not great for memory and disk usage. The rest of the talk, presented by Nicolas, focused on trying to understand behavioral changes by looking at anonymized backend data across companies. One specific insight was that people’s work days have lengthened over the year. Cynically, the promise of “working less because of AI” has not materialized: in fact, we are all seemingly working longer hours and with fewer chunks of focus time, so the dangers of burnout are higher. Maggie Lou from BuildBuddy presented Taking Humans Out of the Build Loop . The premise was that coding agents have improved quickly, but people still spend too much time copy/pasting logs, triggering builds, explaining failures, and reviewing the results. In her presentation, we witnessed many new features in BuildBuddy to allow agents (and humans!) to interact and diagnose remote builds with ease: to download filtered logs for a build. to answer questions such as “Why was my build slow?” which are extremely common in the Bazel ecosystem. to start a remote Firecracker VM and run Bazel inside of it. The VMs are snapshotted for quick reuse, and the runners can execute arbitrary commands rather than Bazel alone. to diagnose a failed build and either create a pull request or push a commit with the proposed correction. to perform a review and post comments to GitHub. The need for these features is unsurprising this late in 2026, but what’s really useful in their offering is how these features integrate with build data. Inspecting the BEP, profiles, remote execution metadata, and logs in unison via an agent can yield much better diagnostics and automated improvements than staring at just a few lines of console output. One thing that surprised me in chatting with the presenter is that BuildBuddy is not particularly big in terms of headcount but they churn out features at a very high rate—and that was true even before AI. Impressive! Armando Montanez (and Ulf Adams, but he didn’t make it) from EngFlow presented Proving Equivalence in any2bazel Build System Migrations . The talk described a structured way to use AI agents for build system migrations and started with a reflection: AI agents used to be terrible at Bazel less than a year ago, but now they do pretty damn well—especially if you can close the loop with automated validations. However, even if agents do well at writing Bazel builds, the fidelity of a migration leaves a lot to be desired if left unattended. And here is where any2bazel comes into play: it turns the process into a guess-and-verify loop. The initial focus of the tool are CMake-to-Bazel migrations, and the tool comes with a script that extracts reference compiler and linker actions from CMake in a deterministic manner. The agent then writes Bazel build files, runs , and feeds the resulting actions to a differ tool that compares those to the originals. The loop continues until the two action sets are equivalent. The equivalence checks are what’s hard though: there are compiler flags that may have no impact on the result, for example, so they need to be “ignored” to let the agent experiment with different Bazel-native approaches until it gets to bit-for-bit identical outputs. It’s important to focus on comparing outcomes and not internals so that the generated Bazel builds do not necessarily follow ancient idioms, like e.g. a Maven-like project structure in a Bazel build. In the end, though, this approach works surprisingly well. But the question is: “How good are the generated build files?” The presenters evaluated them along four axes: Correctness: Good, because equivalence is the central constraint of the loop. Hermeticity: Good, but you might need to do extra upfront work to remove host-specific behavior from the reference build before starting. Efficiency: Usually good when standard rules can model the build. Complex projects with custom build rules may end up with overly large Bazel actions though. Maintainability: Unsurprisingly, the weakest point. Agents tend to model variation with configuration flags instead of proper platforms and toolchains, which is not idiomatic to Bazel. Expert review of AI outputs remains critical, which is, again, not surprising. As a side note, it seems like the team likes pain because they tried to migrate an MSBuild project too. MSBuild is more painful than others because its binary log requires running through a real build: there is no dry-run mode, so it might be difficult to extract a truly clean log of actions, and the process is slow. Fortunately, the reference needs to be extracted only once before the comparison agentic loop can start, and it works: we saw a POC migration of the Color Picker tool that comes from PowerToys. When optimizing a distributed build system, it’s easy to focus on the costs of the remote execution workers: how many there are, what kinds of hardware they use, how well they auto-scale… but a significant driver in cost comes from the storage systems required to support those workers. In other words: the remote cache is expensive. Let’s look at a few topics that deal with this problem. Tyler French from BuildBuddy and Benjamin Ingberg from Meroton presented Content-Defined Chunking for Bazel . This was one of the most immediately-practical talks for anyone operating a remote cache, and it surely caught my eye because I had just been troubleshooting a problem at work that CDC would have prevented in the first place. The problem is that Bazel has traditionally treated each file as one indivisible blob. If an action produces a one-gigabyte binary (not uncommon these days huh) and this binary only changes by a few bytes from a previous build, the client or remote worker must re-upload the entire new file to the CAS and the CAS must store a full copy of those bytes. This is inefficient network- and storage-wise because the cache has to be overprovisioned so that these very large, rarely reused blobs don’t prematurely evict valuable cache entries. Content-defined chunking (CDC) divides a file into variable-sized pieces that can be cached independently. To compute the chunks, a rolling hash scans the contents and chooses boundaries when the hash matches a particular condition. Because the boundaries depend on the content rather than fixed offsets, inserting a few bytes in the middle of a file shifts only the nearby chunks instead of invalidating every subsequent one. With CDC, Bazel represents the original file as a list of chunk offsets and digests instead of a single digest, and each chunk is uploaded or downloaded independently. The presenters reported average reuse of chunks of 36%, chunks of 40%, chunks of 96%, chunks of 98%, and chunks of 99.5%. Furthermore, BuildBuddy estimates that CDC saves 35% of bytes written, deduplicates 60% of chunked bytes, and avoids about 400 TB of traffic per day across its fleet. Finally, the median project sees about 70% less remote storage, while local disk caches shrink by roughly 40%. Impressive numbers. Almost all of these benefits can be achieved by enabling CDC on the backend alone without changes to Bazel because most savings come from worker-to-CAS communication. But there are improvements to be made on the client too, of course. CDC fits bb-clientd especially well because chunks can be reused across output bases and, to materialize a file, the client needs only its chunk map. This can be much cheaper than reconstructing the whole file on every incremental build. For existing users, the starting point is together with a server that supports remote CDC. You’ll want to use the latest Bazel 8.x or 9.x releases for best results, as earlier versions didn’t perform the necessary validations to ensure that CDC didn’t corrupt data. The talk ended with a plea for tool authors to rethink binary formats: files that contain absolute pointers in them are poison for caching even with CDC because small changes in a file can have cascading effects across it. Wherever possible, relative pointers are better. Lore is Epic Games’ open-source, content-addressed version control system for very large, asset-heavy monorepos. Mattias Jansson from Epic Games came on stage to talk about it. But this was not just a presentation of the version control system. This was also a presentation of how Lore integrates with Bazel to prevent ferrying large assets between Lore repositories, the machine running Bazel, and the remote execution/cache cluster. The insight is that Lore and Bazel’s remote cache are both backed by a CAS… so if they can share the same storage, artifacts don’t need to move around. The idea relies on the fact that Bazel-the-client does not need to know the content of source files. All Bazel needs to know are the digests of those files to detect file changes across builds and to compose Remote Execution (RE) API requests. You’d imagine that computing digests requires reading the files, and you’d be right… but the server (Lore) already has those files, can compute their digests once, and can expose those to Bazel for consumption. So, what Epic Games has built is a translation layer between the RE API and Lore’s chunked content addresses, plus a virtual file system that exposes the precomputed digests to Bazel. In this way, Bazel talks to just one storage system and can leverage digests without computing them itself. Of interest was a brief note that Bazel can now use BLAKE3 instead of SHA-256 for content digests, which can likely be a big deal for performance because the former excels in speed due to parallel chunk processing. TIL. Caleb Froese from Canva presented Diffing Millions of Screenshots a Day, Hermetically . The premise of the talk is that, when developing a UI, you really want to have regression tests for how the UI looks —and doing that at scale is difficult. The idea is simple, though: make the code render a part of your UI, capture a screenshot, and compare it against a known-good image. Check in the golden image into source control, and call it a day. Except… if you do that at Canva’s scale, you end up growing the Git repository by about 20 GB per day , which is obviously untenable due to how Git works. A different approach is to store the images elsewhere and expose them to tests through an external repository rule. This integrates well with Bazel in the sense that the downloads are out of the execution path, but it also scales poorly: too much data must be downloaded to each client just for it to be re-uploaded right away to remote executors. And it also creates friction for developers when defining the build graph. In the end, Canva’s solution is to use the Build Event Service and the remote CAS to keep the assets outside of Git while preserving hermetic tests. This pattern applies to any test suite with large golden artifacts, not screenshots alone. Similar story to what Lore tries to fix. There is one extra wrinkle to worry about: GPU-based rendering introduces tiny output differences that make pixel-perfect image comparisons difficult. Canva’s solution is to pin these tests to a specific hardware class by selecting an execution pool through the execution property. That trades scheduling flexibility for reproducible images, which is a good compromise for their workload. Optimizing the way Bazel handles large artifacts helps with performance, but there are many other things that do too. There were a large number of talks around this topic, so let’s dive into some of them. Guillaume Maudoux from Tweag presented Taming Configurations Explosion , a practical talk addressing problems they’ve seen while supporting builds that target physical hardware boards. Such builds grew to have more than three million configured actions even though only about 500,000 distinct actions needed to run. The root problem is that configuration settings accumulate. A project may begin with a setting for the target platform, then add the board’s operating system, its physical layout, its capabilities, and so on. Every setting creates a new dimension in the configuration space and, because each configuration gets a distinct output-tree hash, apparently-different actions may in fact do identical work. Before you know it, you have blown up the action graph and possibly your disk space too. In the example from the talk, 12 parameters end up representing 72 million possible configurations. Only 856 of those configurations matter, and a particular source file has just 39 meaningful ways to be compiled. The rest is duplication introduced by the model. There are three main tools to fight this: Reset transitions: These discard irrelevant configuration values as early as possible in the graph. The art is to move decisions up the dependency tree so that downstream targets do not carry unnecessary dimensions. The trade-off is that ordinary output can become unmanageable, forcing users toward . But then… requires a configuration, so some targets may not be queryable at all without one. Path mapping: If two actions cannot be made identical during analysis, Bazel can rewrite configuration-specific paths during execution and replace their hashes with a stable component. This should be seen as a measure of last resort, though, because subtle problems arise. For example, if the same logical path comes from different files from different configurations, Bazel disables path mapping silently. Tweag fixed Bazel so that different copies of the same file don’t disable path mapping, but debuggability continues to be a problem when this condition does not apply. Flag scopes: This new feature allows a flag to declare where in the graph it applies and to automatically reset to its default everywhere else. This is similar to a reset transition but requires less manual graph plumbing. On the other hand, describing the correct scope can sometimes be harder than writing the transition directly. Han-Wen Nienhuys from EngFlow presented Horapha: Your Personal Warm Bazel , a clever experiment to avoid repeatedly starting Bazel servers and rebuilding their in-memory state. Several CI systems already offer similar features for efficiency, but Horapha targets developer-initiated workflows. The idea is to snapshot a warmed-up Bazel JVM with a new command and save that to disk. A later either starts a normal server when no checkpoint exists or restores the snapshot and continues from the saved state. The implementation relies on CRIU (Checkpoint/Restore In Userspace) , a Linux-only technology that can serialize a running process to disk. Correct restoration requires preserving process IDs, which can be achieved by placing Bazel in a PID namespace. In other words: a container but without pulling in the full weight of Docker. The prototype is available in the Horapha repository with the corresponding Bazel changes in the horapha branch of Han-Wen’s Bazel fork . Han-Wen is now trying to carve a path to get this integrated into upstream Bazel. Did you know that Emacs works similarly? Your executable is actually a snapshot of the LISP machine computed during the build process and stored to disk by the portable dumper introduced in Emacs 27. John Cater and Antonio Di Stefano from EngFlow presented Persistent Test Runners . For a long time, Bazel has had persistent workers for compilation actions but supporting tests has remained elusive—yet persistent workers for tests promise to increase test performance significantly by reducing JVM startup times, sharing heavyweight fixtures across tests, and sharing state such as container images. The reason I said elusive is because Bazel has tried to solve this before. Twice. Google introduced a persistent test feature back in 2019 but it was rolled back that same day. The roll forward was attempted again a month later, already in 2020, but this time separating the feature flag from the runner. Unfortunately, the whole mechanism was scrapped in 2022 because it never worked reliably. The old design suffered from classpath problems after incremental builds, leaked state between tests, and was tightly coupled to Bazel’s native rule—an unacceptable constraint due to the desire to move all rules to Starlark. More fundamentally, the test protocol and the persistent worker protocol modeled very different things. The new proposal from EngFlow introduces an API that explicitly separates the settings and inputs used to create the runner from the data needed by one test request. That distinction is important because the runner infrastructure must be able to decide whether an existing JVM is still compatible with a new test. The team explored several alternatives along the way: Pre-warming the next JVM instead of keeping the current one alive. This provided more control over when and why to restart a test in a new JVM, but suffered from significant coordination overhead. Forking a JVM. This did not work because, due to POSIX semantics, only the calling thread survives a fork call. The JVM is heavily multithreaded, so if you end up losing all but one thread, the new JVM is just not going to work. Android’s Zygote. This provides a pre-warmed runtime ready to be forked ( , anyone?), but it exists only for ART, not the standard JVM, and it’s just not reasonable to expect a switch to ART. Checkpointing. Instead of forking a running process, why not snapshot it to disk so that it can be re-created again? This might have worked, like Horapha does for Bazel startup, but raised difficult questions about when to capture the process and how to handle state outside the JVM. In the end, the only piece that survived these experiments was the coordinator that asks the runner whether a JVM can be reused. The decision considers the Java executable, JVM options, driver code, plugin configuration, and the digests of all loaded JARs. Configurable hooks run at JVM start/stop events as well as before/after each test. When running Bazel’s own test suite, this approach reduced total test time by 46%. The prototype is available in the branches of TheGrizzlyDev/bazel and TheGrizzlyDev/rules_java . It can be tried with a local module override and . Unconference discussion topic proposals and votes for the second day. Remote execution BoF Chi Wang and Tiago Quelhas led the Remote Execution Birds of a Feather . I only stayed for half of it, and so I only captured the discussion around remote persistent workers. Persistent workers are already part of several commercial remote execution offerings, including BuildBuddy and EngFlow, but their implementation was derived from Bazel’s local persistent worker support, which is not… particularly well designed. For example, we have at least three different variants of the persistent worker protocol: one for “regular” persistent workers, another for multiplex persistent workers, and yet another for multiplex persistent workers that support cancellation. And the protocol does not clearly specify which flags and tools belong to the worker and which belong to the action being executed. In fact, these distinctions are currently determined heuristically, with the worker assuming that flag files correspond to the action and other flags to the worker. There was consensus that this should be cleaned up, but the unsatisfying conclusion is that rehashing these complaints and discussions is not going to lead anywhere until someone sits down and presents a specific proposal for a new API. So, if you are reading this and have… opinions… volunteer to do this. Helen Altshuler from EngFlow and Nikita Chepanov from Plaid presented Where Bazel Clusters Break at Scale: Field Notes from Plaid and the EngFlow Fleet . That’s quite a mouthful to say “load testing”. And the reason is none other than AI once again: Plaid’s build volume doubled during the year due to AI-assisted coding and is on track to reach four times its early-2026 baseline. With a predictable increase in load comes a predictable outage. So, instead of waiting for it to happen organically, Plaid deliberately chose to load-test their CI system. The goal was to reach multiples of the normal load and discover each bottleneck under controlled conditions. They had to go through six rounds of tests and fixes until they were able to sustain their desired target. The previous five uncovered problems in network bursts, AWS quotas, source control, CI autoscaling, and cache infrastructure. The solutions were not magical: find and raise limits, cache everything possible, and reduce demand where it does not add value. Examples of the last category include skipping tests for pull requests in the middle of a PR stack and avoiding uploads for actions when they are unlikely to be reused. An interesting observation is that Plaid runs EngFlow in Plaid’s own AWS account, so the cache cluster is co-managed. But careful: shared ownership can easily turn into ambiguous ownership. The two companies addressed this by agreeing on health metrics and thresholds upfront and putting them on a shared dashboard. Both sides now know who must act before developers notice an outage. Ah, one of my favorite topics. Back in my Google days, I spent at least three years of my so-called 20% time working on improving the performance of the Bazel sandbox on macOS. Those efforts were painful: creating a writable FUSE file system is difficult, and diagnosing mis-interactions with macOS was a horrifying exercise. Today, I’m not scared anymore: I’ve been recently using AI to write yet another file system at work and agents do exceedingly well at handling corner cases. Let’s see how modern solutions do better than what I originally tried. David Zbarsky from OpenAI presented actiond: The Quest for a Better Sandbox , which was the first of at least two talks on improving sandboxing performance and strictness. The project started from frustration with local sandbox escapes on macOS and eventually grew into a custom file system, a local virtual machine, and a Bazel-built Linux kernel. actiond pretends to be a remote executor, but the “remote” worker is a Linux VM running locally on the Mac. Bazel communicates with it over a and actiond implements both execution and a content-addressable store. Funnily enough, leveraging this VM for action execution results in faster Bazel builds on macOS than running actions natively. Inside the VM, actiondFS mounts a directory described by a protocol buffer and creates the action sandbox without building a forest of links. Same idea as my original sandboxfs , but the key difference is that actiondFS is a kernel module rather than a FUSE file system so it solves all performance and deployment problems I originally faced with FUSE. A mind-blowing mention was linux.bzl : a Bazel-native build of the Linux kernel, used in this project to build the actiond VM end-to-end with Bazel. This reminds me that I’ve been saying, since the inception of Bazel, that this build system is the perfect pairing for a monorepo like NetBSD’s or FreeBSD’s; and, in fact, I recently wanted a Bazel-native build of NetBSD to put the EndBOX together. I wonder how difficult it would be to hack something up these days with AI… Oh, and: . This flag finally replaces the super-complex script that Bazel uses to run a test with a native binary. This resolves some compatibility issues across platforms and should result in measurably faster test execution. Borja Lorente from Byte Bard Software presented The Sandbox Is a Filesystem: Content-Addressed Bazel Builds on macOS with FSKit , yet another talk on sandboxing and macOS. The immediate problem they tried to address was sandbox escapes in TypeScript builds. You might not be aware, but there happen to be some tools out there that, when faced with a symlink, decide to resolve the target of the symlink and then perform extra operations on that location, like finding sibling files and the like. The compiler is one such tool, and consequently, escapes the symlink-based sandbox used on macOS and behaves incorrectly. Aspect originally patched the JavaScript rules to intercept Node.js file-system calls and redirect them, but that solution stopped working when was rewritten in Go. Apple’s new FSKit framework should in theory be usable to solve this, as it’s “just” a new way of writing file systems in user space. If we could leverage FSKit, the idea then becomes simple: represent the sandbox as a file system and mount a content-addressed view of the action’s inputs within it. Identical subtrees across actions share nodes, contents are fetched lazily, and outputs write through to the host volume. You know, exactly like my own sandboxfs did back in the day with FUSE. Unfortunately, FSKit comes with its own set of problems: An FSKit extension ships as an application, which must be packaged and notarized. This might be OK, but what’s bad is that, because this comes from an application, macOS displays a TCC (Transparency, Consent, and Control) popup notification when an app such as the Terminal tries to access the FSKit volume. Not cool for automated (CI) deployments. Mounting takes hundreds of milliseconds, making a separate mount per action too expensive. This can be solved by reusing the same mount across actions and making the file system create different subtrees per sandbox. Again, like the original sandboxfs. User space file systems have… unavoidable overheads as most operations have to cross the kernel/user space boundary at least twice. These may or may not be acceptable. With my own FUSE-based solution years ago, I just couldn’t fix some performance issues due to some oddities in OSXFUSE. AMFI and Gatekeeper inspect each executable once , adding substantial latency on first execution. And because any executable exposed through a separate file system looks brand new to the kernel… performance tanks. My original sandboxfs mitigated this by keeping inode numbers stable across different instances of the same file across different sandboxes, but that’s what ultimately led to the blockers I encountered with OSXFUSE. Because of all these problems, FSKit was not the clear choice for a new sandboxfs, so the team evaluated alternatives for performance like pure file copying, the old symbolic links, hard links, and APFS’ . FSKit was best at creating the initial directory structure, but later operations such as , , and were slower than with the alternatives. The conclusion was that there is no perfect answer to a fast and secure sandbox on macOS. Symlinks are fastest but allow some tools to escape. Hard links are the second-best option but they cannot protect source files against writes and only work within one volume. is efficient but limited to APFS and, again, one volume. FSKit provides the right abstraction with frustrating deployment and runtime costs. Because of this, the outcome of the talk is a proposal for a new sandboxfs protocol , not a specific implementation. Namely: a way for Bazel to send a manifest describing the inputs plus settings such as network access to a sandbox service. With that, the service can create the sandbox directory and return its path; Bazel can execute the action; and the service can then report the outputs and tear the sandbox down. Different backends can implement the same protocol using the best mechanism for each machine. I like the proposal and the fact that what was old is new again, but there were two interesting questions from the audience. One was: “What about an NFSv4 server?”, which is how Buildbarn exposes efficient virtual file systems on macOS; and the other was: “Can we not implement a new protocol and instead reuse the RE API?” Switching gears to the more theoretical aspects behind Bazel, we can look at changes to a core piece of the ecosystem: the Starlark language. The star (wink, wink) of the show in this area were type systems. Alexandre Rostovtsev from Google presented Static types in Starlark , an update on the type system first discussed during an unconference session at BazelCon 2025. Bazel 8.8 and 9.3 parse the new annotations but otherwise treat them as no-ops, allowing rulesets to adopt the syntax without breaking those releases. Bazel 10 will check annotated files and type-checking should be enabled by default by the time the final release ships. The syntax is a subset of Python’s type annotations with extensions to support Starlark’s native types like providers and attributes, both of which require typed exhaustive dictionaries. This should make large rulesets easier to navigate and maintain, and it lays the foundation for better automated tooling. Right after Google’s update on native Starlark types, Tamir Duberstein from OpenAI presented Type-checking Starlark without waiting for Bazel . I originally read this title as “type-checking without starting a slow Bazel process”—but no, the “waiting for Bazel” part here refers to the fact that the original type-system feature request was filed six (!!) years ago, not addressed in a timely manner, and the ecosystem could not simply stand still until the Bazel team decided to do something. During these six years, Buck 2 has come up with type annotations and a full-featured LSP for their Starlark variant. On the Bazel side, starpls implements another language server and type checker, but its annotations live in comments and the resulting experience is not ideal. OpenAI’s approach is sty , which combines ideas from with ty , the Python type checker developed by Astral. This new project provides fast cross-file checking, resolution, editor integration, and go-to-definition support while avoiding dependencies on a particular Bazel release. One difficulty is that, even if Starlark looks like Python, it isn’t Python: Bazel gives the language several domain-specific semantics. For example, a rule’s fields have types, mandatory status, and default values derived from the rule declaration. A generic Python checker knows none of this, so has to model it explicitly. By “pure” coincidence, OpenAI’s choices here do not diverge much from Google’s official typing system, so there is a path towards reconciliation. The project also introduces files, which act like external stub files and describe types for dependencies without modifying their source. These are particularly useful for rulesets that must continue to support Bazel versions that cannot parse type annotations, because the annotations can live out of sight from Bazel. The last topic I have notes on are talks about rulesets, but I do not have a lot. Let’s just cover a couple of the talks I did attend and take notes from. David Zbarsky from OpenAI presented : {Fast, Hermetic, Ergonomic} — Pick 3 , a new Rust ruleset built to address the pain points that OpenAI encountered with at scale. The usual dependency flow takes and , creates a synthetic workspace, runs , and generates a Bazel-specific . Repinning is slow—roughly O(n^2) in the size of the dependency graph—and Bazel has to repeatedly ask Cargo to contact registries and download metadata. rules_rs avoids that architecture. Bazel already has a downloader and lockfile, so the new ruleset leverages those directly and performs dependency discovery only once per platform. At OpenAI, repins dropped from about ten minutes to 100 milliseconds and can happen as part of an ordinary . Build configuration is read from , avoiding a separate Bazel lock file and the need to keep generated configuration in sync with Cargo. Rust build scripts remain a challenge because they can perform arbitrary work but appear to Bazel as one opaque action. For example, OpenAI replaced the build script in with a dedicated bzlmod module so that Bazel could see and schedule the underlying work. The ruleset also builds the Rust standard library from source, which enables Tier 3 targets and tools such as Miri . Combined with a hermetic LLVM toolchain, can cross-compile projects such as Selenium to Linux, macOS, and Windows. The question from the audience was simple: “What is the carrot for choosing over Cargo?” And the answer was simple as well: at OpenAI, they observed that everything in CI that did not use Bazel was falling over under agent-generated load. Antonio Di Stefano and Yannic Bonenberger from EngFlow presented No Bytes Left Untracked—Bazel Supply Chain Security . The key message was that, while we have always worried about correct builds and Bazel delivers on them, that’s just not enough anymore. We must also be able to explain where every byte comes from and enforce policy over their provenance in order to defend against security threats. Supply-chain attacks are becoming more frequent, and frameworks such as SLSA cover the complete software development lifecycle rather than compilation alone. They include requirements around review, provenance, and Software Bills of Materials (SBOMs). Bazel has always been in a unique position to provide this provenance information because it has a precise dependency graph and runs actions in controlled environments. But a common difficulty is that, outside of Google, Bazel interacts with other ecosystems: third-party package managers bring their own manifests and lock files and coordinating those with Bazel is difficult. There is no uniform representation of package identity, licensing, or provenance. The supply-chain ruleset addresses this with a standard target. The goal is for every package in the Bazel Central Registry to expose its identity and attributes, including licensing information, through a small JSON representation. The presenters asked for help in achieving this, as annotating packages is tedious and, ultimately, the responsibility of their owners. The processing model looks like this: A “gather” aspect walks the target graph of the artifact that needs to be shipped. Each dependency contributes metadata through a transitive provider, effectively producing a serialized view of the relevant graph. Tools convert that data into standard SBOM formats such as SPDX and CycloneDX. Validation actions enforce organization-specific policy, such as banning a particular license from entering a product. This is useful, but the target graph alone cannot fully account for all bytes in an output. True end-to-end attestation also has to inspect the action graph and the environment in which those actions run. Questions like these are to be expected: Which tools transformed the inputs? Where did the actions run? Did those environments have known kernel vulnerabilities? The project roadmap includes rules, module extensions, macro definitions, and stricter build-level enforcement. The 1.0 release was scheduled to happen during BazelCon, but unfortunately they’ll be a few days late due to last-minute issues with documentation and the like. And that’s all I captured this year. There were many other sessions—including talks on hermetic LLVM, Zig package integration, Gazelle v2, CUDA compilation, and richer platforms—but I either did not attend them or did not take enough notes to write anything of substance. Apologies if I did not cover yours here. Check the official BazelCon 2026 schedule for the complete program and stay tuned for the production-grade recordings . Photo while running towards Amsterdam Centraal. The common thread across the conference was scale. AI agents are multiplying the number of builds, tests, and changes that our infrastructure must process, while Bazel users continue to push larger graphs through increasingly-specialized execution environments. The good news is that the ecosystem is responding: Bazel 10 brings meaningful core improvements, remote execution keeps getting smarter, and the BUILD Foundation gives community work a place to grow. But even if the ecosystem is responding, you must too. Bazel is positioned to be a great answer to scalability issues in development workflows thanks to its safe cross-machine, cross-user caching features. And Bazel is also a good way to remain secure amid the unprecedented number of changes to your third-party dependencies. If you have not yet considered Bazel, the best time to do so is today. Stay tuned for the next article! I got some really cool swag from one of the vendors and I promised them I’d write something up once I had a chance to evaluate it. Welcome to BazelCon 2026 sign. What follows is a recollection of my notes arranged by topic and intermixed with my own commentary and thoughts. Some sections and topics are more detailed than others because in some cases I didn’t have a seat and couldn’t type enough, and in others I got distracted in the hallways chatting with people. Speaking of people, several of you approached me to praise previous editions of these recaps, so I now feel obliged to write another one. Thanks for the kind comments! As we will see, “scale” was a central theme of the conference: AI is multiplying concurrent builds and tests, artifacts and graphs are growing at an accelerated pace due to new features like configuration transitions, and the ecosystem is responding by making execution, caching, and analysis more efficient. My highlights There is a lot to cover but here are a few things that felt memorable to me : The BUILD Foundation is now a reality, giving the Bazel ecosystem a vendor-neutral home. Its goal is to act as a proxy between the community and Google to help Google understand what to prioritize and to fund projects. If your company can spare “a few” dollars, please donate! AI-driven development is having a broad impact on the industry and, in particular, everyone is seeing their CI systems become overloaded. Well, news at 11: I’m dealing with this day in and day out. But what was new to me was that we at Snowflake are not the only ones struggling with local system overload. Lots of people out there have likewise “discovered” Git worktrees as a way to run multiple agents in parallel, which in turn means multiple concurrent Bazel servers. Bazel 10 is shaping up to be a substantial release that will help with the problem right above due to its many performance improvements and memory consumption optimizations. Have you struggled to keep Bazel up-to-date before? These days, if you want to get any platform-related work funded you have to spin it in terms of AI, so this release will be an easy sell. Let’s “Rewrite it in Rust”? I’m impressed. Google is seriously evaluating a progressive rewrite of Bazel in Rust, and this is probably the most exciting news I got out of the conference. You know I’ve been critical of Bazel’s usage of Java since day one so, if this takes off, I’ll be the first in line to evaluate the results (and it will likely push me to actually contribute to Bazel again). Fast and correct sandboxing on macOS remains a problem. This is “interesting” to me because it’s a problem I tried to fix almost ten years ago with the original sandboxfs, but I failed because of unexpected bugs in macOS’s FUSE support and eventually abandoned the idea when FUSE became a dead end on Apple’s platforms. Funnily enough, other folks have now reinvented sandboxfs—and even given it the same name (ugh)—and there is even another implementation of a similar idea in the form of actiondFS. Types are coming to Starlark, but Bazel’s late arrival to the party means that multiple competing approaches now exist. We have at least two LSPs with different annotation mechanisms and Buck 2’s own syntax. Hopefully they can all converge. Platforms and configurations remain difficult to model at scale. Careless use of transitions and build settings can produce an explosion of configured actions. Apparently, as one speaker noted, AI agents love transitions for some reason, which is interesting because they are not a popular feature and they are not particularly easy to use. Agents run more builds more frequently than humans, discover and invoke targets that were often “internal only”, and explore several approaches in parallel. Your intuition about how to evaluate which builds matter and how to measure them is probably wrong by now. Bazel and IDEs have never played great together and maybe that just doesn’t matter anymore. We are seeing a sharp decline in IDE usage, although developers still want a way to browse code changes and debug them. This means LSPs are key now to support “leaner” IDEs, and maybe standalone debuggers. Short build and test latency is critical when a human must remain focused on a coding task but, in an agentic workflow, the constraints are different. You know that, after you hit “execute this plan”, the agent will take many minutes to return so minimal build latency is not as important. And actually… maybe you now want to trade some latency in exchange for extra validations so that agents have to take fewer turns to converge. And because humans are now waiting for agents to finish for long periods of time, they have to fill that time with other tasks, which has driven them to adopt Git worktrees en masse. This is leading to scalability problems on dev machines because multiple concurrent Bazel server processes are not great for memory and disk usage. to download filtered logs for a build. to answer questions such as “Why was my build slow?” which are extremely common in the Bazel ecosystem. to start a remote Firecracker VM and run Bazel inside of it. The VMs are snapshotted for quick reuse, and the runners can execute arbitrary commands rather than Bazel alone. to diagnose a failed build and either create a pull request or push a commit with the proposed correction. to perform a review and post comments to GitHub. Correctness: Good, because equivalence is the central constraint of the loop. Hermeticity: Good, but you might need to do extra upfront work to remove host-specific behavior from the reference build before starting. Efficiency: Usually good when standard rules can model the build. Complex projects with custom build rules may end up with overly large Bazel actions though. Maintainability: Unsurprisingly, the weakest point. Agents tend to model variation with configuration flags instead of proper platforms and toolchains, which is not idiomatic to Bazel. Expert review of AI outputs remains critical, which is, again, not surprising. Reset transitions: These discard irrelevant configuration values as early as possible in the graph. The art is to move decisions up the dependency tree so that downstream targets do not carry unnecessary dimensions. The trade-off is that ordinary output can become unmanageable, forcing users toward . But then… requires a configuration, so some targets may not be queryable at all without one. Path mapping: If two actions cannot be made identical during analysis, Bazel can rewrite configuration-specific paths during execution and replace their hashes with a stable component. This should be seen as a measure of last resort, though, because subtle problems arise. For example, if the same logical path comes from different files from different configurations, Bazel disables path mapping silently. Tweag fixed Bazel so that different copies of the same file don’t disable path mapping, but debuggability continues to be a problem when this condition does not apply. Flag scopes: This new feature allows a flag to declare where in the graph it applies and to automatically reset to its default everywhere else. This is similar to a reset transition but requires less manual graph plumbing. On the other hand, describing the correct scope can sometimes be harder than writing the transition directly. Pre-warming the next JVM instead of keeping the current one alive. This provided more control over when and why to restart a test in a new JVM, but suffered from significant coordination overhead. Forking a JVM. This did not work because, due to POSIX semantics, only the calling thread survives a fork call. The JVM is heavily multithreaded, so if you end up losing all but one thread, the new JVM is just not going to work. Android’s Zygote. This provides a pre-warmed runtime ready to be forked ( , anyone?), but it exists only for ART, not the standard JVM, and it’s just not reasonable to expect a switch to ART. Checkpointing. Instead of forking a running process, why not snapshot it to disk so that it can be re-created again? This might have worked, like Horapha does for Bazel startup, but raised difficult questions about when to capture the process and how to handle state outside the JVM. Unconference discussion topic proposals and votes for the second day. Remote execution BoF Chi Wang and Tiago Quelhas led the Remote Execution Birds of a Feather . I only stayed for half of it, and so I only captured the discussion around remote persistent workers. Persistent workers are already part of several commercial remote execution offerings, including BuildBuddy and EngFlow, but their implementation was derived from Bazel’s local persistent worker support, which is not… particularly well designed. For example, we have at least three different variants of the persistent worker protocol: one for “regular” persistent workers, another for multiplex persistent workers, and yet another for multiplex persistent workers that support cancellation. And the protocol does not clearly specify which flags and tools belong to the worker and which belong to the action being executed. In fact, these distinctions are currently determined heuristically, with the worker assuming that flag files correspond to the action and other flags to the worker. There was consensus that this should be cleaned up, but the unsatisfying conclusion is that rehashing these complaints and discussions is not going to lead anywhere until someone sits down and presents a specific proposal for a new API. So, if you are reading this and have… opinions… volunteer to do this. Where Bazel clusters break at scale Helen Altshuler from EngFlow and Nikita Chepanov from Plaid presented Where Bazel Clusters Break at Scale: Field Notes from Plaid and the EngFlow Fleet . That’s quite a mouthful to say “load testing”. And the reason is none other than AI once again: Plaid’s build volume doubled during the year due to AI-assisted coding and is on track to reach four times its early-2026 baseline. With a predictable increase in load comes a predictable outage. So, instead of waiting for it to happen organically, Plaid deliberately chose to load-test their CI system. The goal was to reach multiples of the normal load and discover each bottleneck under controlled conditions. They had to go through six rounds of tests and fixes until they were able to sustain their desired target. The previous five uncovered problems in network bursts, AWS quotas, source control, CI autoscaling, and cache infrastructure. The solutions were not magical: find and raise limits, cache everything possible, and reduce demand where it does not add value. Examples of the last category include skipping tests for pull requests in the middle of a PR stack and avoiding uploads for actions when they are unlikely to be reused. An interesting observation is that Plaid runs EngFlow in Plaid’s own AWS account, so the cache cluster is co-managed. But careful: shared ownership can easily turn into ambiguous ownership. The two companies addressed this by agreeing on health metrics and thresholds upfront and putting them on a shared dashboard. Both sides now know who must act before developers notice an outage. Sandboxing and local execution Ah, one of my favorite topics. Back in my Google days, I spent at least three years of my so-called 20% time working on improving the performance of the Bazel sandbox on macOS. Those efforts were painful: creating a writable FUSE file system is difficult, and diagnosing mis-interactions with macOS was a horrifying exercise. Today, I’m not scared anymore: I’ve been recently using AI to write yet another file system at work and agents do exceedingly well at handling corner cases. Let’s see how modern solutions do better than what I originally tried. actiond: the quest for a better sandbox David Zbarsky from OpenAI presented actiond: The Quest for a Better Sandbox , which was the first of at least two talks on improving sandboxing performance and strictness. The project started from frustration with local sandbox escapes on macOS and eventually grew into a custom file system, a local virtual machine, and a Bazel-built Linux kernel. actiond pretends to be a remote executor, but the “remote” worker is a Linux VM running locally on the Mac. Bazel communicates with it over a and actiond implements both execution and a content-addressable store. Funnily enough, leveraging this VM for action execution results in faster Bazel builds on macOS than running actions natively. Inside the VM, actiondFS mounts a directory described by a protocol buffer and creates the action sandbox without building a forest of links. Same idea as my original sandboxfs , but the key difference is that actiondFS is a kernel module rather than a FUSE file system so it solves all performance and deployment problems I originally faced with FUSE. A mind-blowing mention was linux.bzl : a Bazel-native build of the Linux kernel, used in this project to build the actiond VM end-to-end with Bazel. This reminds me that I’ve been saying, since the inception of Bazel, that this build system is the perfect pairing for a monorepo like NetBSD’s or FreeBSD’s; and, in fact, I recently wanted a Bazel-native build of NetBSD to put the EndBOX together. I wonder how difficult it would be to hack something up these days with AI… Oh, and: . This flag finally replaces the super-complex script that Bazel uses to run a test with a native binary. This resolves some compatibility issues across platforms and should result in measurably faster test execution. The sandbox is a filesystem Borja Lorente from Byte Bard Software presented The Sandbox Is a Filesystem: Content-Addressed Bazel Builds on macOS with FSKit , yet another talk on sandboxing and macOS. The immediate problem they tried to address was sandbox escapes in TypeScript builds. You might not be aware, but there happen to be some tools out there that, when faced with a symlink, decide to resolve the target of the symlink and then perform extra operations on that location, like finding sibling files and the like. The compiler is one such tool, and consequently, escapes the symlink-based sandbox used on macOS and behaves incorrectly. Aspect originally patched the JavaScript rules to intercept Node.js file-system calls and redirect them, but that solution stopped working when was rewritten in Go. Apple’s new FSKit framework should in theory be usable to solve this, as it’s “just” a new way of writing file systems in user space. If we could leverage FSKit, the idea then becomes simple: represent the sandbox as a file system and mount a content-addressed view of the action’s inputs within it. Identical subtrees across actions share nodes, contents are fetched lazily, and outputs write through to the host volume. You know, exactly like my own sandboxfs did back in the day with FUSE. Unfortunately, FSKit comes with its own set of problems: An FSKit extension ships as an application, which must be packaged and notarized. This might be OK, but what’s bad is that, because this comes from an application, macOS displays a TCC (Transparency, Consent, and Control) popup notification when an app such as the Terminal tries to access the FSKit volume. Not cool for automated (CI) deployments. Mounting takes hundreds of milliseconds, making a separate mount per action too expensive. This can be solved by reusing the same mount across actions and making the file system create different subtrees per sandbox. Again, like the original sandboxfs. User space file systems have… unavoidable overheads as most operations have to cross the kernel/user space boundary at least twice. These may or may not be acceptable. With my own FUSE-based solution years ago, I just couldn’t fix some performance issues due to some oddities in OSXFUSE. AMFI and Gatekeeper inspect each executable once , adding substantial latency on first execution. And because any executable exposed through a separate file system looks brand new to the kernel… performance tanks. My original sandboxfs mitigated this by keeping inode numbers stable across different instances of the same file across different sandboxes, but that’s what ultimately led to the blockers I encountered with OSXFUSE. A “gather” aspect walks the target graph of the artifact that needs to be shipped. Each dependency contributes metadata through a transitive provider, effectively producing a serialized view of the relevant graph. Tools convert that data into standard SBOM formats such as SPDX and CycloneDX. Validation actions enforce organization-specific policy, such as banning a particular license from entering a product.

0 views
Blog System/5 3 months ago

An old-new take on argument parsing in Rust

Over the years, I’ve written tens of command-line applications in many different languages—shell is probably the top contender, believe it or not—and for various ecosystems. Along the way, I’ve developed… let’s say… opinions on how they should behave . But behavior and implementation are different topics, and today I would like to talk a little about the latter in the Rust ecosystem. A big theme behind those opinions is that consistency usually wins: when designing an application, you should target an ecosystem and make sure the tool feels “at home” within it instead of reinventing the way it accepts arguments or presents help. But what is the ecosystem? Is it the language the tool is written in, or… is it the set of tools with which it plays? For example: if you were to write a command-line application in Go, you’d naturally reach for the built-in library to define flags. Doing so would make the tool feel normal to other Go developers and would make it easier to “read” to them—but the end user does not care, dare I say… at all , which language your tool is written in. So if they try to use such a tool in the context of standard Unix tools like those provided by coreutils or textutils, your tool will feel out of place. And that is what matters to me: I develop tools for a certain ecosystem, not for a language, and I want those tools to integrate well no matter which language they are written in. I mentioned Go right above because Go is the prime example of opinionated choices that “leak” in various ways. This article is about Rust, however, so let’s switch languages. But before we do, take a moment to subscribe to Blog System/5 to demonstrate your support. It’s free if you want it to be! When writing Rust command-line applications, the expectation nowadays—or rather, assumption—is that you’ll use the crate to parse options and arguments. Funnily enough, this assumption is so ingrained in the ecosystem that, when I asked a late-2025 coding agent to review a codebase of mine, it hallucinated that I was using even when such crate was nowhere to be found. Here is what a simple -based hello world app looks like: Sample clap-based tool. On the left, the source code. On the right, an invocation without arguments and one invoking help. I will not deny that the resulting app looks nice and that the declarative idiom to define this interface is concise and very powerful. But the result is… out of place with other programs because of all these colors (I know they can be disabled). Also, the code is a bit too magical, as usually happens with -style libraries (I know you can opt out of that). And yet… even with all the bells and whistles, the library doesn’t provide enough mechanisms to define an app “end to end”. You see: Rust’s can return an , which is enough to report success or failure to the caller, but this still leaves the application’s control flow in your hands. Because you have to explicitly call within , there is no guarantee that you do it at “the right time”: you might be tempted to parse config files before parsing arguments and other nasty things like that, which can then lead to weird behavior like not working if the config file is malformed or on an unavailable network drive. isn’t the only game in town though. There are indeed other Rust libraries to parse command lines, with being another popular choice. Some of these are also built around derives, some make different tradeoffs around help text and output style, and some smaller alternatives focus mostly on parsing options . This is all fine, but it still doesn’t give me the small Unix-y framework I wanted: something that treats options and positional arguments as one interface, validates both consistently, and owns the startup sequence from parsing to exit code. For all of the reasons above, I’ve developed “my own ways” to parse options and arguments in Rust so that they align with more traditional Unix-y programs. In doing so, I ended up writing my own library. I initially wrote this library in the context of the EndBOX where I had to implement various system services and wanted: to enforce consistency among them with as little code duplication as possible, and to ensure integration into the host’s ecosystem of Unix-y tools provided by the NetBSD base image. I called that library at the time and, in the fall of 2025, I thought of cleaning it up a little and publishing it. So, today, I want to belatedly announce . Mind you, I had drafted this article back in November but never published it, so today is the day. Better late than never. You might be thinking that is quite a mouthful, and even an ugly name. And you know what? That’s true. But the name is what it is because builds on and extends the ancient getopts , in the tradition of Unix-like systems. is largely unused today in the Rust ecosystem—except for the tiny little fact that itself uses it. OK, OK, if you want me to be perfectly honest… the reason exists at all is because is what I originally picked up in 2016 when I started learning Rust based on my previous knowledge of the POSIX and the GNU libc functions… and I never switched gears. is basically a wrapper over , extending it to offer argument-parsing facilities. Where leaves you with a list of free-form strings to validate by hand, lets you: declare positional arguments with cardinality constraints, validates those constraints for you, prints them as a distinct section in the generated help, and provides helpers for common application metadata such as version, bug-reporting, home page, and manual-page information. As such, its API tries to follow the same interfaces that offers, which means I’ve kept original names intact and modeled my own extensions in a similar fashion. This leads to rather cryptic method names and suboptimal Rust interfaces, but again, I tried to mimic as much as possible. What I’ve changed, however, is the way in which you should use the library. provides an “end-to-end” framework to define the method of an application, and it does so with three pieces. The first is the application , which is a struct that implements the builder pattern to register application metadata, options, and arguments. The second is the command-line , which extends the struct for parsed options with access to parsed arguments. And the third is an macro that facilitates writing the scaffolding for , delegating to a couple of functions. A sample, full-featured program looks like this: And then we can run it in various ways: You might still say: there is too much magic in those macros and builders! And you’re right, so you can also define the same app using imperative code and avoid all of that. To see how, I’ll refer you to the various upstream examples . I do not intend for this crate to replace the nicer or or the other libraries that exist out there. Heck, I do not even expect any of you to want to use it. But I still have a use for something like this in my own programs, and I wanted to factor out the code I had already written into a cohesive standalone piece, so I had to publish the crate. Head to https://github.com/jmmv/getoptsargs/ for more details! Is it the language the tool is written in, or… is it the set of tools with which it plays? Sample clap-based tool. On the left, the source code. On the right, an invocation without arguments and one invoking help. I will not deny that the resulting app looks nice and that the declarative idiom to define this interface is concise and very powerful. But the result is… out of place with other programs because of all these colors (I know they can be disabled). Also, the code is a bit too magical, as usually happens with -style libraries (I know you can opt out of that). And yet… even with all the bells and whistles, the library doesn’t provide enough mechanisms to define an app “end to end”. You see: Rust’s can return an , which is enough to report success or failure to the caller, but this still leaves the application’s control flow in your hands. Because you have to explicitly call within , there is no guarantee that you do it at “the right time”: you might be tempted to parse config files before parsing arguments and other nasty things like that, which can then lead to weird behavior like not working if the config file is malformed or on an unavailable network drive. isn’t the only game in town though. There are indeed other Rust libraries to parse command lines, with being another popular choice. Some of these are also built around derives, some make different tradeoffs around help text and output style, and some smaller alternatives focus mostly on parsing options . This is all fine, but it still doesn’t give me the small Unix-y framework I wanted: something that treats options and positional arguments as one interface, validates both consistently, and owns the startup sequence from parsing to exit code. Enter simpler times For all of the reasons above, I’ve developed “my own ways” to parse options and arguments in Rust so that they align with more traditional Unix-y programs. In doing so, I ended up writing my own library. I initially wrote this library in the context of the EndBOX where I had to implement various system services and wanted: to enforce consistency among them with as little code duplication as possible, and to ensure integration into the host’s ecosystem of Unix-y tools provided by the NetBSD base image. declare positional arguments with cardinality constraints, validates those constraints for you, prints them as a distinct section in the generated help, and provides helpers for common application metadata such as version, bug-reporting, home page, and manual-page information.

0 views
Blog System/5 4 months ago

Autoconf’s revenge: ad-hoc shell templates

As powerful as Bazel is, sometimes it’s not featureful enough. When using this build system, it’s common practice to wrap it in a launcher script—and in fact, this is natively supported by Bazelisk , Bazel’s native dispatcher that stands for the binary in the user’s . Bazelisk will first download the version of Bazel requested by the project, and then, if exists, invoke it instead of the downloaded binary. is what’s known as a Bazel wrapper and is the point of today’s article. Well, not quite. The actual point of today’s article is to demonstrate a simple trick I learned from the GNU Autoconf and Automake days to implement full-blown conditionals in an ad-hoc template system. But because such trick is trivial once you see it, I have to present it in the context of a modern real-world scenario. So what I’m going to do is guide you through the creation of your very own Bazel wrapper to customize Bazel’s configuration file in ways that the native Bazel tool doesn’t support. Let’s get started. But wait! Take a moment to subscribe. I’m sure you’ll enjoy future posts, and it’s the only way for me to know that they are worth writing in the first place! Template systems are everywhere. Take any static blog generation system and you’ll find some. Take system management tools like Ansible and you’ll find others. Take a cloud orchestration service like Kubernetes and you’ll find Helm. Heck, even Go’s standard library provides a full blown text template system out of the box. There is clear benefit and appetite for these and, surely enough, it’s tempting to use any pre-existing such system in your own project… but if all you need are a bunch of variable replacements, some of which may be only conditionally applied, you can go a long way by not taking any dependencies. A call to or the substring function of your language of choice is all you need. To put this in context, let’s say you have Bazel’s configuration file, which is not very flexible, and that you need to set some arguments based on dynamic values that depend on the environment. E.g. something like this: If you know a little bit about , however, you may squint at that and say: “That’s silly! Make those flags conditional on a configuration and you’re set!” So you try something like this: And… this does not work. Gotcha! Startup flags cannot be placed behind a configuration so there is no way for you to parameterize the JVM’s max heap value passed in . And having to remember to pass from CI all the time is fragile, because you might forget and not get the desired configuration in place. Solving the above is not difficult if we could parameterize the configuration. We might want to write something like this instead: … and then have and be replaced dynamically depending on some runtime arbitrary logic. We can do that via the Bazel wrapper, and this sort of dynamic configuration is a common thing to do from it. So let’s do this. Let’s start with the template logic: Ugly(?) bash syntax but nothing too complicated: The global hashmap tracks variable names and their replacement values. The function inserts a new key/value pair into . (It’s important that the values given to don’t contain -special characters like , backslashes, or the separator we chose—but we control the generation of those values so we are good.) The function transforms the hashmap into a set of arguments of the form and then calls to process the given input file into the given output file. Then, we can plug everything together into a minimal Bazel wrapper: In this new snippet, the function instantiates the file from the contents of via and then calls the actual Bazel binary provided by Bazelisk in . The complexity here may seem overkill, but it’s necessary : while it’s pointless to invoke Bazel in parallel due to its global lock, users will run Bazel in parallel and you must make sure that the wrapper is reentrant. Otherwise, you’ll definitely run into races. The rest of the script in does the actual work to compute key/value pairs to substitute in your now-templated and then delegates to Bazel via . That’s it. This is a barebones implementation of a text template system using bash—and I had to use bash, not sh, to get the niceties of a hashmap —that serves as a launcher. Go try it. By the way, the and nomenclature are inherited from GNU Autoconf’s AC_SUBST primitive . “Great!” I hear you say in a sarcastic tone. “You have just applied string replacements! But what about conditionals, huh? You CaNnOt Do ThAt So EaSiLy!!11!one!” Ah, but you can , and showing you that trick is the whole point of this short article, remember? The necessary insight is that we can use string replacements to comment out lines in the original file. What if we did this: In here, we are defining different configurations for developer workstations and for CI, like we did earlier, but then we are auto-magically picking the default configuration depending on and . How? Well: will expand to the empty string when running on CI and will expand to , so the corresponding lines will be enabled and disabled. And the opposite replacement values will appear when not running on CI. Ta-da! Conditionals. We can make things nicer with a helper function and meta-programming: Don’t panic about that . Just as with the invocation above where we could have issues with special characters appearing in values, we control the arguments to so the is safe. And note that we can even nest conditionals arbitrarily. There is nothing preventing you from doing: Which corresponds to the conceptual equivalent of: Let’s do loops? Sorry no, can’t do! Well akshually… we could do loops. Not by using simple tricks like above, but we could definitely sketch something like this: However, this is starting to look a lot like a high-level parser, not scripting where you glue simpler components together. And if you are headed that way, you are better off transitioning to a proper programming language and a well-known template system. What do you think? Do you hate this already? You can, but note that the whole world runs on this stuff. All of that foundational code behind Linux systems ends up using GNU Automake and GNU Autoconf, and those packages are full of stuff like this in their and files. And you can get very far with just the above constructs if you treat the shell like a real language . The Bazel wrapper that I maintain at work these days grew to almost 1000 lines of code before I pruned a lot of features that had become unnecessary, but it’s still pretty large. We are now transitioning it to a Go-based wrapper for better readability and maintainability… but as we do this, I’m reminded that well-groomed shell scripts give you some flexibility that no other language can match in just a few lines. So, keep things simple. You can do a lot with just a few primitives. As powerful as Bazel is, sometimes it’s not featureful enough. When using this build system, it’s common practice to wrap it in a launcher script—and in fact, this is natively supported by Bazelisk , Bazel’s native dispatcher that stands for the binary in the user’s . Bazelisk will first download the version of Bazel requested by the project, and then, if exists, invoke it instead of the downloaded binary. is what’s known as a Bazel wrapper and is the point of today’s article. Well, not quite. The actual point of today’s article is to demonstrate a simple trick I learned from the GNU Autoconf and Automake days to implement full-blown conditionals in an ad-hoc template system. But because such trick is trivial once you see it, I have to present it in the context of a modern real-world scenario. So what I’m going to do is guide you through the creation of your very own Bazel wrapper to customize Bazel’s configuration file in ways that the native Bazel tool doesn’t support. Let’s get started. But wait! Take a moment to subscribe. I’m sure you’ll enjoy future posts, and it’s the only way for me to know that they are worth writing in the first place! The context Template systems are everywhere. Take any static blog generation system and you’ll find some. Take system management tools like Ansible and you’ll find others. Take a cloud orchestration service like Kubernetes and you’ll find Helm. Heck, even Go’s standard library provides a full blown text template system out of the box. There is clear benefit and appetite for these and, surely enough, it’s tempting to use any pre-existing such system in your own project… but if all you need are a bunch of variable replacements, some of which may be only conditionally applied, you can go a long way by not taking any dependencies. A call to or the substring function of your language of choice is all you need. To put this in context, let’s say you have Bazel’s configuration file, which is not very flexible, and that you need to set some arguments based on dynamic values that depend on the environment. E.g. something like this: If you know a little bit about , however, you may squint at that and say: “That’s silly! Make those flags conditional on a configuration and you’re set!” So you try something like this: And… this does not work. Gotcha! Startup flags cannot be placed behind a configuration so there is no way for you to parameterize the JVM’s max heap value passed in . And having to remember to pass from CI all the time is fragile, because you might forget and not get the desired configuration in place. Basic string replacements Solving the above is not difficult if we could parameterize the configuration. We might want to write something like this instead: … and then have and be replaced dynamically depending on some runtime arbitrary logic. We can do that via the Bazel wrapper, and this sort of dynamic configuration is a common thing to do from it. So let’s do this. Let’s start with the template logic: Ugly(?) bash syntax but nothing too complicated: The global hashmap tracks variable names and their replacement values. The function inserts a new key/value pair into . (It’s important that the values given to don’t contain -special characters like , backslashes, or the separator we chose—but we control the generation of those values so we are good.) The function transforms the hashmap into a set of arguments of the form and then calls to process the given input file into the given output file.

5 views
Blog System/5 5 months ago

Is anyone still using Emacs?

In a recent discussion at the orange site sparked by the Emacs 31 Is Around the Corner: The Changes I’m Already Daily Driving article, people were asking themselves “Is anyone still using Emacs?” and then providing their own perspective. For me, the answer is a resounding yes… but the interesting part is that I’m not still using Emacs: I’m actually using Emacs again . And instead of burying my answer to the opening question in a long discussion thread, I thought I’d explain my journey with and without Emacs for the last… almost 30 years. At the end, I’ll unveil the specific feature that I feel gives me superpowers and that keeps me hooked. Show your support for this publication by subscribing. It’s free if you want it to be! I got into Linux around 1997 via Caldera OpenLinux 1.1. Before then, I had extensively played with Borland Turbo C++ and Visual Basic as a kid so I was heavily accustomed to those fancy IDEs that we lost . As I got into Linux and found myself in an alien world, I had to buy a couple of introductory books. Yes, books, the printed kind—because that’s how we had to learn new stuff before. Both books talked about Vim and Emacs and presented them as the advanced choices. I found this strange because the IDEs I had used before seemed more complete, but I, being a Windows renegade for some reason, charged ahead. I learned the basics of both editors and went through their tutorials at different times. The two old books I used to learn Linux back in the day, open to show their Vim and Emacs introductions. Since then and until roughly 2015, I flip-flopped between Vim and Emacs. At times I used one, and at times I used the other. I favored Emacs for long-running coding sessions but Vim excelled at my pkgsrc work where I had to edit tens of different files in quick succession. Even though Vim and Emacs worked well for me, I missed something. Language integration was poor so I was tempted by the more modern editors that everyone was touting, and especially so as I moved to macOS. I tried a bunch, like the now-defunct Atom and Brackets , but they all felt brittle and overwhelming: they had too many features, too many settings. And then, VSCode arrived in 2015. As I took it for a test drive, it “felt right” from the get-go. It looked modern, was relatively small, and its plain and simple settings editor—read: just a JSON file because there were no settings panels yet!—made me feel like I was in control. I could understand this modern editor and easily tune it to my needs. Soon after, I started learning Go and then Rust, and VSCode’s integration with their corresponding LSPs made that process so much easier: code auto-completion and real-time error highlighting sped up my learning significantly. I stuck with VSCode for these languages and slowly phased Emacs out. I was sold. During that time period, I was also working on Bazel—a Java project—at Google and the natural choice for it was IntelliJ. I had tried to use Emacs for Java development at some point, but IntelliJ was (and still is) so good that it was the only realistic choice. My usage of VSCode with its Vim plugin continued through my short stint at Microsoft, where I was working on a C++ codebase and had to connect to remote Windows boxes. Most people used RDP to work on the remote machine “directly”, but I couldn’t stand that workflow: I very much preferred running VSCode on my desktop and using SSH to connect to the remote machine, which is something that VSCode does very well. And then… I moved to Snowflake in 2022 where development used to happen inside an ancient Linux VM and where my day-to-day job was to write shell scripts and Bazel build files: neither VSCode nor IntelliJ were going to save me here, and as I mentioned earlier, I hate the feeling of working within the constraints of a “remote” graphical environment. So my instinct was to go back to SSH and connect to the local VM with it. As I did that, I needed an editor for long work sessions, and the old and trusty Emacs was there waiting for me. But this time around, I didn’t have the patience to set it up. You see: I had accumulated hundreds of lines in my file over the years without understanding much about them, and I wanted to throw it all away and start over… but it all felt like too much work. Maybe destiny brought Doom Emacs my way at the right time. Stock Doom Emacs screenshot from the project's website. You see, Doom Emacs is an Emacs “distribution” where someone has gone through the pain (or joy, I won’t judge) of configuring Emacs from the ground up. More specifically, Doom Emacs offers sane defaults, predefined language integrations, and an experience that welcomes ex-Vimers. It doesn’t claim to be an IDE… but it feels like one to me. Once I set it up, I experienced déjà-vu: Emacs felt right just like VSCode did in 2015. All of a sudden, lots of Emacs features became discoverable via interactive popup menus accessible behind space-based shortcuts that don’t destroy your wrists, and coexisting with the same Vim-style key bindings that I had grown so used to. But what’s more: the configuration felt simple and understandable, spread across just three trivial files: to specify global settings like the theme or the fonts to use, to select which Doom-specific modules need to be enabled, and to install non-Doom packages. The defaults for these files are reasonable, with plenty of comments to configure the few details you might want to tune. With this new setup, I have had the best Emacs experience ever. Thanks to the advances in LSPs (for which we have to thank VSCode) and modern features like tree-sitter, Emacs now feels like an IDE: I get proper language integration for most languages I have to deal with. And the absolute killer feature for me is that I get the exact same development environment no matter what machine I need to work on. It doesn’t matter if it is a MacBook or a Linux laptop, or if I’m connecting to a Linux cloud workstation or even my own FreeBSD server: all I need is a shell, tmux, and Emacs, and I am equally productive. This, to me, is really valuable because I tend to work on a variety of machines and muscle memory pays off. If you research Doom Emacs online, you will find people “complaining” that “it does too much”. And that’s true: it does, which is why I find it so useful. But I often wonder if I could cut things down because someday I’d like to learn more about Emacs. This is especially true now that I see many modern third-party modules “graduating” and becoming part of the stock package. For those reasons, I’ve recently been tempted to try the Bedrock or Emacs Solo distributions. However… the activation energy required to make the switch is pretty damn high. And if I decided to go that route, well, I’d still question myself for not truly going all the way to “raw” Emacs. And before closing, a related thought: I can’t quite comprehend how Emacs becomes transformative for people due to its Elisp backing. Sure, I could implement more logic and workflows within Emacs, but I already do “everything” with ease in the shell via scripts—and scripts feel more Unix-y because “Unix is my IDE”. I actually don’t like how Org mode and Magit are “locked” behind Emacs instead of being standalone applications. I’m surely missing something, but I’m not quite sure what it is… So coming back to the question that opened the article: yes, I still use Emacs, and it has become even more important to me than it was in the past due to my need to work on disparate remote machines all the time. Now the questions for you are: do you “still” use it too? What distribution, if any? How does Emacs transform your workflows? Now that you have made it this far, consider subscribing and/or sharing this article in your favorite social platform for further discussion! The two old books I used to learn Linux back in the day, open to show their Vim and Emacs introductions. Since then and until roughly 2015, I flip-flopped between Vim and Emacs. At times I used one, and at times I used the other. I favored Emacs for long-running coding sessions but Vim excelled at my pkgsrc work where I had to edit tens of different files in quick succession. The switch to VSCode and IntelliJ Even though Vim and Emacs worked well for me, I missed something. Language integration was poor so I was tempted by the more modern editors that everyone was touting, and especially so as I moved to macOS. I tried a bunch, like the now-defunct Atom and Brackets , but they all felt brittle and overwhelming: they had too many features, too many settings. And then, VSCode arrived in 2015. As I took it for a test drive, it “felt right” from the get-go. It looked modern, was relatively small, and its plain and simple settings editor—read: just a JSON file because there were no settings panels yet!—made me feel like I was in control. I could understand this modern editor and easily tune it to my needs. Soon after, I started learning Go and then Rust, and VSCode’s integration with their corresponding LSPs made that process so much easier: code auto-completion and real-time error highlighting sped up my learning significantly. I stuck with VSCode for these languages and slowly phased Emacs out. I was sold. During that time period, I was also working on Bazel—a Java project—at Google and the natural choice for it was IntelliJ. I had tried to use Emacs for Java development at some point, but IntelliJ was (and still is) so good that it was the only realistic choice. My usage of VSCode with its Vim plugin continued through my short stint at Microsoft, where I was working on a C++ codebase and had to connect to remote Windows boxes. Most people used RDP to work on the remote machine “directly”, but I couldn’t stand that workflow: I very much preferred running VSCode on my desktop and using SSH to connect to the remote machine, which is something that VSCode does very well. Back to (Doom) Emacs And then… I moved to Snowflake in 2022 where development used to happen inside an ancient Linux VM and where my day-to-day job was to write shell scripts and Bazel build files: neither VSCode nor IntelliJ were going to save me here, and as I mentioned earlier, I hate the feeling of working within the constraints of a “remote” graphical environment. So my instinct was to go back to SSH and connect to the local VM with it. As I did that, I needed an editor for long work sessions, and the old and trusty Emacs was there waiting for me. But this time around, I didn’t have the patience to set it up. You see: I had accumulated hundreds of lines in my file over the years without understanding much about them, and I wanted to throw it all away and start over… but it all felt like too much work. Maybe destiny brought Doom Emacs my way at the right time. Stock Doom Emacs screenshot from the project's website. You see, Doom Emacs is an Emacs “distribution” where someone has gone through the pain (or joy, I won’t judge) of configuring Emacs from the ground up. More specifically, Doom Emacs offers sane defaults, predefined language integrations, and an experience that welcomes ex-Vimers. It doesn’t claim to be an IDE… but it feels like one to me. Once I set it up, I experienced déjà-vu: Emacs felt right just like VSCode did in 2015. All of a sudden, lots of Emacs features became discoverable via interactive popup menus accessible behind space-based shortcuts that don’t destroy your wrists, and coexisting with the same Vim-style key bindings that I had grown so used to. But what’s more: the configuration felt simple and understandable, spread across just three trivial files: to specify global settings like the theme or the fonts to use, to select which Doom-specific modules need to be enabled, and to install non-Doom packages.

1 views
Blog System/5 6 months ago

A Markdown-based test suite

This article is not about AI and it is not written with AI, but the work that I’m about to present was definitely motivated by AI. And because I generally like telling stories, I have to give you that background. Do with that whatever you want, but… it’d be a pity if you left just because the AI word showed up in the first paragraph! I think the technical explanation that follows is at the very least entertaining and also interesting independently of AI. Back in December, I started toying with coding agents. One thing I tried, and for which I didn’t expect a lot of success, was to point an AI agent to the EndBASIC public documentation and ask it to write games like Space Invaders or Mario from scratch. And even though the results weren’t perfect and they didn’t work on the first try, they did work with a few tiny tweaks. Combining that with a bunch of hand-written rules, I had an agent producing EndBASIC demos with ease. This experiment was impressive because I did not expect an agent to be able to write EndBASIC code… and because it worked, it fueled my interest to pick EndBASIC’s own development back up. Three thoughts came to mind: Increase EndBASIC’s “self-documenting” aspects so that an AI agent can learn about its idiosyncrasies unsupervised. Speed up EndBASIC so that it can run more elaborate games. Extend EndBASIC with long-desired primitives like sprites and sound, to finally realize the vision behind the project. These thoughts combined sparked the rewrite of EndBASIC’s core that I’ve been pursuing since January and which should see the light of day in the upcoming release. But before that happens, I want to talk to you about just one of the cool pieces behind the new core: namely, its approach to testing. I’ve stopped writing unit tests for the compiler and VM in Rust and I’ve switched to writing them in Markdown. And I believe this has turned out to be a pretty nice approach. One of the things I had to do to convince an AI agent to write proper EndBASIC code was to hand-craft a bunch of rules to tell it how EndBASIC differs from other, more traditional BASIC dialects. That worked OK, but writing these rules by hand was error-prone and difficult to make exhaustive. So I wanted to let LLMs extract that information directly from EndBASIC. The idea was simple: if I wrote the integration tests for the new core in Markdown, the lingua franca of AI, the tests would serve as the canonical and correct documentation demonstrating language behaviors. LLMs are great at summarizing information, so if I unleashed them over a large set of these hands-on “examples”, they would probably figure stuff out, right? And they actually do! I gave the following prompt to GPT 5.4: Based on your pre-existing knowledge of BASIC dialects, I want you to read all of the files, analyze how the EndBASIC dialect differs from your knowledge, and come up with a bunch of rules for yourself to know how to write EndBASIC code later on. You can ignore the Disassembly sections. Beware that all functions and commands in these integration tests are test-only: the real functions and commands that you can use are documented in , so read those too to learn what functionality is available. Write your findings to a file. And this produced a very comprehensive file with spot-on rules: here, take a look . But leaving that aside, let’s peek into the internals of this new Markdown-based test suite. All cool so far? Want to see more similar content in the future? Subscribe now to demonstrate your interest! It’s a collection of Markdown files: Where each file acts as a container of one or more test cases : Every test case has a section title describing what the test is about and various subsections to define the test scenario: A Source code block that is the input to the compiler. If compilation fails, a Compilation errors section with the error messages and nothing else afterwards. If compilation succeeds: A Disassembly section that contains the compiled bytecode. An optional Exit code section showing the program’s exit code, if different from zero. An Output section that contains any messages printed to the console by the executed program. A Runtime errors section that contains any errors from the executed program. Here is a simple example validating the command: There is no section to validate the lexer nor parser internals right now but I’m considering to further extend the format and dump the AST too in order to simplify the tests for these components. The driver for this test suite enumerates all Markdown files in the tests directory and processes them one at a time. For each file, the driver extracts all test case titles and their Source subsections to compute all the test cases to execute. Once the driver has this subset of information from the Markdown files, the driver feeds each individual test case to the compiler and, if compilation succeeds, to the VM. All side-effects are captured and the driver emits a new Markdown file from scratch with the results of the test. Once the driver has terminated producing a new version of the Markdown file for a test, the driver compares the produced file (actual) against the pre-recorded, checked-in version (golden). If they differ, the test fails and the driver uses the tool to print the differences. And that’s it. Easy peasy, right? This keeps the driver super-simple as the only thing it has to do is parse a minimal subset of Markdown, and the diffs it produces are trivial to understand to a human. There are currently 448 test cases and 13k lines of Markdown in this test suite so maintaining them “by hand” is not an option. You wouldn’t want to implement an optimization to the compiler and then have to rewrite hundreds of disassembly chunks in the golden files to reflect the changes, would you? The thing is that, due to the design described earlier, regenerating the golden files after a core change is easy: the driver is already doing exactly that to execute the tests! The trick is, simply put, to ask the driver to rewrite the golden file instead of producing an actual file by setting the environment variable. And voila: all golden files are regenerated in place. I can then use Git to validate the changes and commit them along with the actual code change. Let’s start with the pros of this Markdown-based test suite framework: It is much easier to work with than what I had before. I used to dread touching the compiler and VM of the previous EndBASIC core implementation because tweaking tens of tests was painful. Changes required me to fiddle with positions and deeply nested types, and now the tests are trivial to tweak and diff against previous state. Pretty much any decent text editor has Markdown support, including formatting fenced code blocks. This makes it easy to skim through the test suite and modify the files and is actually the primary reason I used Markdown instead of a bespoke textual format. LLMs can “learn” with ease. OK, fair, this is just a guess: I did not try the same prompt at the beginning of this article against the old core with its Rust-based tests, and maybe the LLMs would have done a good job at reverse-engineering the rules. But because the Markdown tests are so much easier to read by humans, I have to assume that they also are for LLMs. And now, of course, some cons: Regenerating the output of a test, or all tests, is way too easy . With the older Rust-based tests, I was forced to manually punch in things like line numbers and nested AST trees. This process forced me to think through the changes in detail. With the new approach… regenerating the golden files is trivial, so it’s easy to miss little mistakes in source positions or disassembled code. Differences in disassembly are usually noisy and hard to review because every line carries an address and thus any new or deleted instruction will introduce offsets into all other addresses. I could of course choose to not include the instruction addresses in the dump, but they come in handy when manually validating jump targets, so it felt better to keep them around. Rust cannot generate first-class test cases on the fly which means that the various test cases within a Markdown file are “invisible” to the driver: I can run them all or none, but regular test filtering via doesn’t apply. I was able to “expose” the different Markdown files as different Rust-native test cases, but this involves a hardcoded list of test files—which must be kept in sync with the files on disk, and so I mitigated the chances of divergence by adding a test that cross-references the two. This idea does not generalize well. The Markdown-based test suite presented here works well for components where end-to-end testing is favorable and, more importantly, cheap , but I wouldn’t recommend it for other scenarios. Keeping tests fast is a must for quick iteration. And I think that’s about it. If the above feels too abstract, I encourage you to take a look at the driver , its helper code , and the directory with test suites . Now that you have this new trick up your sleeve, what do you think? Back in December, I started toying with coding agents. One thing I tried, and for which I didn’t expect a lot of success, was to point an AI agent to the EndBASIC public documentation and ask it to write games like Space Invaders or Mario from scratch. And even though the results weren’t perfect and they didn’t work on the first try, they did work with a few tiny tweaks. Combining that with a bunch of hand-written rules, I had an agent producing EndBASIC demos with ease. This experiment was impressive because I did not expect an agent to be able to write EndBASIC code… and because it worked, it fueled my interest to pick EndBASIC’s own development back up. Three thoughts came to mind: Increase EndBASIC’s “self-documenting” aspects so that an AI agent can learn about its idiosyncrasies unsupervised. Speed up EndBASIC so that it can run more elaborate games. Extend EndBASIC with long-desired primitives like sprites and sound, to finally realize the vision behind the project. A Source code block that is the input to the compiler. If compilation fails, a Compilation errors section with the error messages and nothing else afterwards. If compilation succeeds: A Disassembly section that contains the compiled bytecode. An optional Exit code section showing the program’s exit code, if different from zero. An Output section that contains any messages printed to the console by the executed program. A Runtime errors section that contains any errors from the executed program. It is much easier to work with than what I had before. I used to dread touching the compiler and VM of the previous EndBASIC core implementation because tweaking tens of tests was painful. Changes required me to fiddle with positions and deeply nested types, and now the tests are trivial to tweak and diff against previous state. Pretty much any decent text editor has Markdown support, including formatting fenced code blocks. This makes it easy to skim through the test suite and modify the files and is actually the primary reason I used Markdown instead of a bespoke textual format. LLMs can “learn” with ease. OK, fair, this is just a guess: I did not try the same prompt at the beginning of this article against the old core with its Rust-based tests, and maybe the LLMs would have done a good job at reverse-engineering the rules. But because the Markdown tests are so much easier to read by humans, I have to assume that they also are for LLMs. Regenerating the output of a test, or all tests, is way too easy . With the older Rust-based tests, I was forced to manually punch in things like line numbers and nested AST trees. This process forced me to think through the changes in detail. With the new approach… regenerating the golden files is trivial, so it’s easy to miss little mistakes in source positions or disassembled code. Differences in disassembly are usually noisy and hard to review because every line carries an address and thus any new or deleted instruction will introduce offsets into all other addresses. I could of course choose to not include the instruction addresses in the dump, but they come in handy when manually validating jump targets, so it felt better to keep them around. Rust cannot generate first-class test cases on the fly which means that the various test cases within a Markdown file are “invisible” to the driver: I can run them all or none, but regular test filtering via doesn’t apply. I was able to “expose” the different Markdown files as different Rust-native test cases, but this involves a hardcoded list of test files—which must be kept in sync with the files on disk, and so I mitigated the chances of divergence by adding a test that cross-references the two. This idea does not generalize well. The Markdown-based test suite presented here works well for components where end-to-end testing is favorable and, more importantly, cheap , but I wouldn’t recommend it for other scenarios. Keeping tests fast is a must for quick iteration.

0 views
Blog System/5 6 months ago

What if there was no BASIC in EndBASIC?

Six years have passed since I started building EndBASIC : a retro-looking BASIC interpreter that works on the web, on the desktop, and on embedded hardware—and that allows writing cross-platform apps that leverage graphics, a cloud file sharing system, and even access to local hardware via GPIO. But as cool as this sounds, and as exciting as the journey has been, there is something that keeps bugging me about the future of the project: who wants to invest time building something new on an abandoned language? Even Visual Basic, a real platform that evolved over many years and gained “serious language features”, has fallen out of fashion and is, as far as I know, in “maintenance mode” by Microsoft . So I’ve been thinking… “What if there was no BASIC in EndBASIC?” Or, in other words, how could I leverage the many pieces I’ve created underneath this project to build something that people actually want to use, be it for retro-style development or for other purposes? In fact, the BASIC portion of the whole project—that is, the language parser and compiler—is the least interesting one. Yes, I’ve written a BASIC interpreter, but the amount of features my dialect provides today is… limited, and building those up is not the most exciting thing to do. For example: records and files are very much needed features, but adding them is not going to make the project much cooler or useful than it already is. So: let’s look at the building blocks (BBs) behind EndBASIC so that we can imagine how these pieces could be recombined to form something different. At the root of EndBASIC lives a “pure” language core with a relatively simple, non-optimizing (yet) compiler and accompanying VM that can be extended via native Rust bindings and that can be embedded into Rust programs. It’s trivial to leverage this core language to implement imperative DSLs or even dynamic configuration files. What does “pure” mean here, though? Simply put that the core language, implemented as a separate crate with minimal dependencies, has absolutely no function nor command definitions in it. The programs executed by this VM can have no side-effects nor escape the VM by default: all they can do is compute values, maybe based on global variables injected by the host. Consumers of this core crate, like EndBASIC’s standard library, are responsible for implementing all functions and commands that make the language useful—but these are all intentionally kept out of the core. Even fundamental primitives that you would expect a BASIC dialect to provide, like or , are not part of the core language. This poses some difficulties in the implementation of the compiler but they are an explicit design choice to keep the core lean. Underneath EndBASIC’s graphics drawing commands, there is a collection of Rust primitives to interact with a possibly-graphical console. Hybrid graphics/text console running on Firefox. Image from my presentation at BSDCan 2025 . Today, this console runs on various environments, including: The text-based Windows and Unix-like terminals via the library. The SDL library for native desktop graphics support across Windows and Unix-like systems (including macOS and Linux, of course). The HTML5 canvas to target the web browser. The NetBSD wscons framebuffer to target “boot-to-EndBASIC” environments. The ST7735s LCD (but more generally, SPI-based LCDs). For all graphical backends, these Rust primitives provide consistent basic rasterization algorithms for common shapes and support different bitmap fonts. Behind EndBASIC’s file operations lives a Rust library that implements a virtual drive-based file system with multiple implementations for these drives. Right now, drives can be backed by: Memory, like a ram disk. A collection of read-only files hardcoded into the binary. A single directory in the host’s file system. The browser’s local storage. A cloud service. The cloud service drive is backed by the EndBASIC Service, which provides a simple REST API for file access and mutation. Files stored in this drive can be user-private, but they can also be shared with specific users or be made public. Powering the EndBOX , we have a NetBSD base system slimmed down to a minimum set of components with the ability to boot into a graphical application within seconds of powering up the device. The system image has been designed so that it’s possible to access configuration files and user data from Windows and macOS hosts with ease, allowing tuning the system and performing backups without having to access the inner NetBSD OS. In other words: NetBSD is just an implementation detail that is invisible to users of this image. This platform is accompanied by a custom collection of robust build scripts that coordinate compiling NetBSD from scratch with the cross-building of a Rust application that uses the console framework described earlier. These scripts then take care of bundling the cross-built binary into the image and starting it up early in the boot process. You can think of this as a simple version of buildroot but NetBSD-based and explicitly targeted at creating application-specific images for embedded devices. What’s more: in order to support the needs of an application that starts so early in the boot process and to ensure the application can run with the least amount of privileges, the platform provides an RPC mechanism and a privileged daemon that can be used to escalate privileges for specific operations (such as rebooting the machine). And there is also a daemon to optionally collect completely anonymous telemetry (things like version numbers, host architecture, and graphics device in use) from deployed devices. Diagram of the system services provided by the EndBOX. Slide from my presentation at BSDCan 2025 . So, what could we do with these? As you were reading through the four building blocks above, I suspect some ideas might have come to mind about what could be done with these pieces without necessarily keeping the BASIC dialect around. Here are some of mine for how this project could evolve: Continue building the BASIC language up. Yes, of course that’s a possibility! EndBASIC itself is a fun project to work on, and adding more features to it and continuing to build up this retro environment is a never-ending source of joy. Even if I question the point later… Replace BASIC with a real language. As I said earlier, further developing the BASIC dialect is not super interesting, particularly because BASIC is full of warts that make it hard to parse. So what if you got the exact same retro, cross-platform experience that EndBASIC currently offers but based on a real language that people like using these days? Lua is a strong contender… but so could be LISP or Scheme. I don’t know much about the latter two, but knowing that LISP machines used to exist… they could be pretty fitting. Focus on the core. I kinda like the idea of having a pure compiler and VM that can be extended to form DSLs, all written in Rust. So maybe building on this specifically is another possible path? The problem is that there already are more languages in the world than you can imagine, so pursuing this feels like a dead end right from the beginning, and I’m not even sure what it’d mean. A BSD-based buildroot alternative. buildroot works, but it’s based on Linux and comes with the problems that you’d expect from Linux: you are essentially assembling a disparate set of components built by different people with little communication. Putting them together gives you “something”, but it is not cohesive. The platform behind EndBASIC, however, carries an opinionated design for how embedded disk images should be, and provides basic services to enforce security principles, to preserve privacy, and to be performant. So what if you could write a Rust-native program that leveraged my console and file system abstraction primitives, and could deploy it to an embedded device with ease as “a full OS”? Something something AI. There is no denying that AI is here to stay, so I’ve also been wondering how it might be related to EndBASIC. AI coding agents are great for prototyping ideas, and EndBASIC is a great platform to showcase flashy results with very little code. So maybe EndBASIC could become a good target for coding agents so that you could vibecode embedded projects? I wrote this article sometime last year after running out of steam: shipping the EndBOX was a lot of work and, once that was out, I had to take a break. Honestly, it was a bit disappointing to receive so little interest. By Christmas, I picked up the draft and was almost about to publish it. But then… In January, I started working on a full re-implementation of EndBASIC’s core language, because reasons that are not important now. This means that the “next steps” have been decided already, at least for the next few months: this rewrite is landing imminently as I mentioned in the EndBASIC 0.12 release announcement from last week. Once that happens, I’ll want to spend some time building up some features that I’ve been wishing to have but never got to for years. In particular, I want to provide some extra graphics manipulation primitives (primarily for sprites) and I want to finally add sound support. But all other ideas are still on the table, and I’m curious: do any of them pique your curiosity? If you answered yes to the question right above, subscribe to show your support, and make sure to leave a comment below! In fact, the BASIC portion of the whole project—that is, the language parser and compiler—is the least interesting one. Yes, I’ve written a BASIC interpreter, but the amount of features my dialect provides today is… limited, and building those up is not the most exciting thing to do. For example: records and files are very much needed features, but adding them is not going to make the project much cooler or useful than it already is. So: let’s look at the building blocks (BBs) behind EndBASIC so that we can imagine how these pieces could be recombined to form something different. BB1: A pure compiler and VM At the root of EndBASIC lives a “pure” language core with a relatively simple, non-optimizing (yet) compiler and accompanying VM that can be extended via native Rust bindings and that can be embedded into Rust programs. It’s trivial to leverage this core language to implement imperative DSLs or even dynamic configuration files. What does “pure” mean here, though? Simply put that the core language, implemented as a separate crate with minimal dependencies, has absolutely no function nor command definitions in it. The programs executed by this VM can have no side-effects nor escape the VM by default: all they can do is compute values, maybe based on global variables injected by the host. Consumers of this core crate, like EndBASIC’s standard library, are responsible for implementing all functions and commands that make the language useful—but these are all intentionally kept out of the core. Even fundamental primitives that you would expect a BASIC dialect to provide, like or , are not part of the core language. This poses some difficulties in the implementation of the compiler but they are an explicit design choice to keep the core lean. BB2: A portable console framework Underneath EndBASIC’s graphics drawing commands, there is a collection of Rust primitives to interact with a possibly-graphical console. Hybrid graphics/text console running on Firefox. Image from my presentation at BSDCan 2025 . Today, this console runs on various environments, including: The text-based Windows and Unix-like terminals via the library. The SDL library for native desktop graphics support across Windows and Unix-like systems (including macOS and Linux, of course). The HTML5 canvas to target the web browser. The NetBSD wscons framebuffer to target “boot-to-EndBASIC” environments. The ST7735s LCD (but more generally, SPI-based LCDs). Memory, like a ram disk. A collection of read-only files hardcoded into the binary. A single directory in the host’s file system. The browser’s local storage. A cloud service. Diagram of the system services provided by the EndBOX. Slide from my presentation at BSDCan 2025 . So, what could we do with these? As you were reading through the four building blocks above, I suspect some ideas might have come to mind about what could be done with these pieces without necessarily keeping the BASIC dialect around. Here are some of mine for how this project could evolve: Continue building the BASIC language up. Yes, of course that’s a possibility! EndBASIC itself is a fun project to work on, and adding more features to it and continuing to build up this retro environment is a never-ending source of joy. Even if I question the point later… Replace BASIC with a real language. As I said earlier, further developing the BASIC dialect is not super interesting, particularly because BASIC is full of warts that make it hard to parse. So what if you got the exact same retro, cross-platform experience that EndBASIC currently offers but based on a real language that people like using these days? Lua is a strong contender… but so could be LISP or Scheme. I don’t know much about the latter two, but knowing that LISP machines used to exist… they could be pretty fitting. Focus on the core. I kinda like the idea of having a pure compiler and VM that can be extended to form DSLs, all written in Rust. So maybe building on this specifically is another possible path? The problem is that there already are more languages in the world than you can imagine, so pursuing this feels like a dead end right from the beginning, and I’m not even sure what it’d mean. A BSD-based buildroot alternative. buildroot works, but it’s based on Linux and comes with the problems that you’d expect from Linux: you are essentially assembling a disparate set of components built by different people with little communication. Putting them together gives you “something”, but it is not cohesive. The platform behind EndBASIC, however, carries an opinionated design for how embedded disk images should be, and provides basic services to enforce security principles, to preserve privacy, and to be performant. So what if you could write a Rust-native program that leveraged my console and file system abstraction primitives, and could deploy it to an embedded device with ease as “a full OS”? Something something AI. There is no denying that AI is here to stay, so I’ve also been wondering how it might be related to EndBASIC. AI coding agents are great for prototyping ideas, and EndBASIC is a great platform to showcase flashy results with very little code. So maybe EndBASIC could become a good target for coding agents so that you could vibecode embedded projects?

0 views
Blog System/5 8 months ago

I think AI is pushing me toward the AGPL

It has been two months since I’ve been using AI coding agents “for real”. In my previous article , I reflected on my experiment to vibe-code a full Emacs module from scratch. In there, I intentionally left one important question unanswered: what is the meaning and impact of agentic coding on the free software ecosystem we have all grown accustomed to? Right now, I have many thoughts but no good answers, and the reason is that the more I use these tools, the more I doubt my long-held beliefs about open-source licensing. While I’ve found that agentic coding makes me more productive—provided I supervise the agents carefully, in some circumstances—it also distances me from the act of coding itself, stripping away the pride of craftsmanship and thus the desire to publish code as open source. The bigger worry, however, is for the ecosystem as a whole. Let’s dive into what’s on my mind right now. Am I writing about AI now? Yes… Is Blog System/5 written by an agent? No! Subscribe to support human-crafted content. Except for the cover images, sorry. I’ve been into open source for almost 30 years now. My first exposure to the ecosystem was the FIPS utility , which I had to use to install my first Linux distribution (Caldera OpenLinux 1.1 if you are wondering). To young-me, a 13-year old interested in low-level software and having only been exposed to Windows and OS/2, having full access to the source code of a frigging disk manipulation tool and even a full OS was mind-blowing. From that moment on, I took the GPLv2 to heart because access to this ecosystem, vast in size and completely free, felt like a gift. I started publishing my own code as free software, licensed under the GPLv2, and I quickly got involved into existing projects. Not too long after, I joined NetBSD “full-time” because I found in it the perfect balance of “a system that worked well-enough for my day-to-day needs but that had plenty of room for contributions”. As I continued to encroach myself in the BSD ecosystem, I was exposed to many… “discussions” comparing the GPL against BSD-like licenses. I came out believing that the GPL was more restrictive than the BSD licenses because it imposed extra limitations on consumers. As outreach was the (my) goal, I was all-in on licensing my code via BSD-like licenses. Until maybe now. If you ask a modern AI agent to work within the constraints of an established project, you will realize that the agent’s output follows the architecture and coding style of the project extremely closely. The diffs I get back are really similar to what I’d have written by hand. But… even if you don’t prompt the right way, you still get features that work. Slop, probably, but still functional. And that’s what’s rubbing me the wrong way with regards to open source licensing. In the past, when you published a piece of free software, you knew there was some risk that someone could take your code and selfishly benefit from it. But, for the most part, taking a project and modifying it in a way that provided value to users required significant effort . If someone wanted to build on your project and then redistribute it, they had to spend the time to change it and they had to reason about the consequences of their changes, the project’s license, and their own long-term maintenance efforts. With AI? All of that seems gone. It’s just too easy for anyone to pick an existing project, run it through an agent to customize, fork, and ship it out. Zero need for any real time investment. Zero consideration for what was there in the first place. Zero need to worry about future maintenance because agents will just pile onto whatever they did before and, to users, it will all seem to work. So, here I am, starting to question my long-held thoughts on copyleft licenses. As I said above in my personal story, I grew up believing that BSD licenses were the better choice for true software freedom. But now? Is it really a good idea to ship BSD-like licensed code anymore? The chances of a slop fork happening are way too real, and the consequences dire: after all, said fork will be able to display tons more features with ease, gain traction, and the pressure against upstream to “do something about them, quickly!” will be a thing. Left unattended, any interest and community around the original project may vanish. And the reason I’m writing this article is because there is this disturbing thought in my mind right now: should I flip 180 degrees and start licensing my future code as… no less than the “evil” AGPLv3 ? I have usually avoided this license, but it sounds like it is the only chance at protecting projects from slop (commercial) forks. But then what? Suppose you publish your project as AGPLv3. Suppose a downstream consumer forks the project and starts building on top of it with immense velocity thanks to AI agents. And suppose they have no problem with keeping the project open source per the license. Their changes may be slop, but they may be delivering features that users have wanted for a long time—and let’s face it, the vast majority of people have little consideration for software quality or performance. In this situation, as the upstream, what do you do? Do you try to incorporate the vibe-coded changes with the massive effort that this requires? Or do you ignore them and hope that they go away, collapsing under their own complexity weight? The truth, I suspect, is that they won’t go away, so you as upstream may become irrelevant very quickly unless you can keep up with the “contributions” being made. Whether you care or not depends on why you published your code as free software in the first place, and different authors have different motivations. So what else can you do? Maybe you make the project’s test suites proprietary and keep them secret. In an AI-powered world, test suites are THE secret sauce to keep agents on track, so if you don’t publish yours, slop forks will have a hard(er) time staying aligned with upstream. Unfortunately, keeping test suites secret is logistically difficult and annoying, plus it goes against the very tenets of a free software project. No easy choices here… I have several more thoughts on the topic of AI and how it affects open source, particularly regarding contributions and the feeling that they can easily lead to burnout, but in this article I wanted to focus purely on the licensing choices. I want to close this not with answers, but with a recap of the questions that would be nice to discuss: If AI can closely mimic your architecture with zero effort, does the “friction of modification” need to be replaced by the legal friction of the AGPL? Is keeping test suites proprietary a legitimate “moat” for human maintainers, or does it violate the core spirit of open source? If we accept that AI agents are a tool and that, properly guided, can produce good PRs at an overwhelming rate, how do we keep up with contributions? If you end up vibe-coding most of a project, does it even make sense to open-source it? Why? What pride is there in that? Share your thoughts in the comments section! It has been two months since I’ve been using AI coding agents “for real”. In my previous article , I reflected on my experiment to vibe-code a full Emacs module from scratch. In there, I intentionally left one important question unanswered: what is the meaning and impact of agentic coding on the free software ecosystem we have all grown accustomed to? Right now, I have many thoughts but no good answers, and the reason is that the more I use these tools, the more I doubt my long-held beliefs about open-source licensing. While I’ve found that agentic coding makes me more productive—provided I supervise the agents carefully, in some circumstances—it also distances me from the act of coding itself, stripping away the pride of craftsmanship and thus the desire to publish code as open source. The bigger worry, however, is for the ecosystem as a whole. Let’s dive into what’s on my mind right now. Am I writing about AI now? Yes… Is Blog System/5 written by an agent? No! Subscribe to support human-crafted content. Except for the cover images, sorry. A little history I’ve been into open source for almost 30 years now. My first exposure to the ecosystem was the FIPS utility , which I had to use to install my first Linux distribution (Caldera OpenLinux 1.1 if you are wondering). To young-me, a 13-year old interested in low-level software and having only been exposed to Windows and OS/2, having full access to the source code of a frigging disk manipulation tool and even a full OS was mind-blowing. From that moment on, I took the GPLv2 to heart because access to this ecosystem, vast in size and completely free, felt like a gift. I started publishing my own code as free software, licensed under the GPLv2, and I quickly got involved into existing projects. Not too long after, I joined NetBSD “full-time” because I found in it the perfect balance of “a system that worked well-enough for my day-to-day needs but that had plenty of room for contributions”. As I continued to encroach myself in the BSD ecosystem, I was exposed to many… “discussions” comparing the GPL against BSD-like licenses. I came out believing that the GPL was more restrictive than the BSD licenses because it imposed extra limitations on consumers. As outreach was the (my) goal, I was all-in on licensing my code via BSD-like licenses. Until maybe now. Friction no more If you ask a modern AI agent to work within the constraints of an established project, you will realize that the agent’s output follows the architecture and coding style of the project extremely closely. The diffs I get back are really similar to what I’d have written by hand. But… even if you don’t prompt the right way, you still get features that work. Slop, probably, but still functional. And that’s what’s rubbing me the wrong way with regards to open source licensing. In the past, when you published a piece of free software, you knew there was some risk that someone could take your code and selfishly benefit from it. But, for the most part, taking a project and modifying it in a way that provided value to users required significant effort . If someone wanted to build on your project and then redistribute it, they had to spend the time to change it and they had to reason about the consequences of their changes, the project’s license, and their own long-term maintenance efforts. With AI? All of that seems gone. It’s just too easy for anyone to pick an existing project, run it through an agent to customize, fork, and ship it out. Zero need for any real time investment. Zero consideration for what was there in the first place. Zero need to worry about future maintenance because agents will just pile onto whatever they did before and, to users, it will all seem to work. So, here I am, starting to question my long-held thoughts on copyleft licenses. As I said above in my personal story, I grew up believing that BSD licenses were the better choice for true software freedom. But now? Is it really a good idea to ship BSD-like licensed code anymore? The chances of a slop fork happening are way too real, and the consequences dire: after all, said fork will be able to display tons more features with ease, gain traction, and the pressure against upstream to “do something about them, quickly!” will be a thing. Left unattended, any interest and community around the original project may vanish. And the reason I’m writing this article is because there is this disturbing thought in my mind right now: should I flip 180 degrees and start licensing my future code as… no less than the “evil” AGPLv3 ? I have usually avoided this license, but it sounds like it is the only chance at protecting projects from slop (commercial) forks. Contribution doubts But then what? Suppose you publish your project as AGPLv3. Suppose a downstream consumer forks the project and starts building on top of it with immense velocity thanks to AI agents. And suppose they have no problem with keeping the project open source per the license. Their changes may be slop, but they may be delivering features that users have wanted for a long time—and let’s face it, the vast majority of people have little consideration for software quality or performance. In this situation, as the upstream, what do you do? Do you try to incorporate the vibe-coded changes with the massive effort that this requires? Or do you ignore them and hope that they go away, collapsing under their own complexity weight? The truth, I suspect, is that they won’t go away, so you as upstream may become irrelevant very quickly unless you can keep up with the “contributions” being made. Whether you care or not depends on why you published your code as free software in the first place, and different authors have different motivations. So what else can you do? Maybe you make the project’s test suites proprietary and keep them secret. In an AI-powered world, test suites are THE secret sauce to keep agents on track, so if you don’t publish yours, slop forks will have a hard(er) time staying aligned with upstream. Unfortunately, keeping test suites secret is logistically difficult and annoying, plus it goes against the very tenets of a free software project. No easy choices here… What do you think? I have several more thoughts on the topic of AI and how it affects open source, particularly regarding contributions and the feeling that they can easily lead to burnout, but in this article I wanted to focus purely on the licensing choices. I want to close this not with answers, but with a recap of the questions that would be nice to discuss: If AI can closely mimic your architecture with zero effort, does the “friction of modification” need to be replaced by the legal friction of the AGPL? Is keeping test suites proprietary a legitimate “moat” for human maintainers, or does it violate the core spirit of open source? If we accept that AI agents are a tool and that, properly guided, can produce good PRs at an overwhelming rate, how do we keep up with contributions? If you end up vibe-coding most of a project, does it even make sense to open-source it? Why? What pride is there in that?

0 views
Blog System/5 8 months ago

Reflections on vibecoding ticket.el

It has now been a month since I started playing with Claude Code “for real” and by now I’ve mostly switched to Codex CLI: it is much snappier—who would imagine that a “Rewrite in Rust” would make things tangibly faster—and the answers feel more to-the-point than Claude’s to me. As part of this experiment, I decided to go all-in with the crazy idea of vibecoding a project without even looking at the code. The project I embarked on is an Emacs module to wrap a CLI ticket tracking tool designed to be used in conjunction with coding agents. Quite fitting for the journey, I’d say. In this article, I’d like to present a bunch of reflections on this relatively-simple vibecoding journey. But first, let’s look at what the Emacs module does. Oh, you saw em dashes and thought “AI slop article”? Think again. Blog System/5 is still humanly written. Subscribe to support it! CLI-based ticket tracking seems to be a necessity to support driving multiple agents at once, for long periods of time, and to execute complex tasks. A bunch of tools have shown up to track tickets via Markdown files in a way that the agents can interact with. The prime example is Beads by Steve Yegge . I would have used it if I hadn’t read otherwise, but then the article “A ‘Pure Go’ Linux environment, ported by Claude, inspired by Fabrice Bellard” showed up and it contained this gem, paraphrased by yours truly: Beads is a 300k SLOC vibecoded monster backed by a 128MB Git repository, sporting a background daemon, and it is sluggish enough to increase development latency… all to manage a bunch of Markdown files. Like, WTH. The article went on to suggest Ticket (tk) instead: a pure shell implementation of a task tracking tool backed by Markdown files stored in a directory in your repo. This sort of simple tool is my jam and I knew I could start using it right away to replace the ad-hoc text files I typically write. Once I installed the tool and created a nixpkgs package for it —which still requires approval, wink wink—I got to creating a few tickets. As I started using Ticket more and more to keep a local backlog for my EndBASIC compiler and VM rewrite, I started longing for some sort of integration in Doom Emacs. I could edit the Markdown files produced by just fine, of course, but I wanted the ability to find them with ease and to create new tickets right from the editor. Normally, I would have discarded this idea because I don’t know Elisp. However, it quickly hit me: “I can surely ask Claude to write this Emacs module for me”. As it turns out, I could, and within a few minutes I had a barebones module that gave me rudimentary ticket creation and navigation features within Emacs. I didn’t even look at the code, so I continued down the path of refining the module via prompts to fix every bug I found and implement every new idea I had. By now, works reasonably well and fulfills a real need I had, so I’m pretty happy with the result . If you care to look, the nicest thing you’ll find is a tree-based interactive browser that shows dependencies and offers shortcuts to quickly manipulate tickets. doesn’t offer these features, so these are all implemented in Elisp by parsing the tickets’ front matter and implementing graph building and navigation algorithms. After all, Elisp is a much more powerful language than the shell, so this was easier than modifying itself. Should you want to try this out, visit jmmv/ticket.el on GitHub for instructions on how to install this plugin and to learn how to use it. I can’t promise it will function on anything but Doom Emacs even if the vibewritten claims that it does, but if it doesn’t, feel free to send a PR. Alright, so it’s time for those reflections I promised. Well, yes! It took more-or-less prodding to convince the AI that certain features it implemented didn’t work, but with little effort in additional prompts, I was able to fix them in minutes. A big part of why the AI failed to come up with fully working solutions upfront was that I did not set up an end-to-end feedback cycle for the agent. If you take the time to do this and tell the AI what exactly it must satisfy before claiming that a task is “done”, it can generally one-shot changes. But I didn’t do that here. At some point I asked the agent to write unit tests, and it did that, but those seem to be insufficient to catch “real world” Emacs behavior because even if the tests pass, I still find that features are broken when trying to use them. And for the most part, the failures I’ve observed have always been about wiring shortcuts, not about bugs in program logic. I think I’ve only come across one case in which parentheses were unbalanced. Certainly not. While learning Lisp and Elisp has been in my backlog for years and I’d love to learn more about these languages, I just don’t have the time nor sufficient interest to do so. Furthermore, without those foundations already in place, I would just not have been able to create this at all. AI agents allowed me to prototype this idea trivially , for literal pennies, and now I have something that I can use day to day. It’s quite rewarding in that sense: I’ve scratched my own itch with little effort and without making a big deal out of it. Nope. Even though I just said that getting the project to work was rewarding, I can’t feel proud about it. I don’t have any connection to what I have made and published, so if it works, great, and if it doesn’t… well, too bad. This is… not a good feeling. I actually enjoy the process of coding probably more than getting to a finished product. I like paying attention to the details because coding feels like art to me, and there is beauty in navigating the thinking process to find a clean and elegant solution. Unfortunately, AI agents pretty much strip this journey out completely. At the end of the day, I have something that I can use, though I don’t feel it is mine. Not really, and supports why people keep bringing up the Jevons paradox . Yes, I did prompt the agent to write this code for me but I did not just wait idly while it was working: I spent the time doing something else , so in a sense my productivity increased because I delivered an extra new thing that I would have not done otherwise. One interesting insight is that I did not require extended blocks of free focus time—which are hard to come by with kids around—to make progress. I could easily prompt the AI in a few minutes of spare time, test out the results, and iterate. In the past, if I ever wanted to get this done, I’d have needed to make the expensive choice of using my little free time on this at the expense of other ideas… but here, the agent did everything for me in the background. Other than how to better prompt the AI and the sort of failures to routinely expect? No. I’m as clueless as ever about Elisp. If you were to ask me to write a new Emacs module today, I would have to rely on AI to do so again: I wouldn’t be able to tell you how long it might take me to get it done nor whether I would succeed at it. And if the agent got stuck and was unable to implement the idea, I would be lost. This is a very different feeling from other tasks I’ve “mastered”. If you ask me to write a CLI tool or to debug a certain kind of bug, I know I’ll succeed and have a pretty good intuition on how long the task is going to take me. But by working with AI on a new domain… I just don’t, and I don’t see how I could build that intuition. This is uncomfortable and dangerous. You can try asking the agent to give you an estimate, and it will, but funnily enough the estimate will be in “human time” so it won’t have any meaning. And when you try working on the problem, the agent’s stochastic behavior could lead you to a super-quick win or to a dead end that never converges on a solution. Of course it is. Regardless, I just don’t care in this specific case . This is a project I started to play with AI and to solve a specific problem I had. The solution works and it works sufficiently well that I just don’t care how it’s done: after all, I’m not going to turn this Emacs module into “my next big thing”. The fact that I put the code as open source on GitHub is because it helps me install this plugin across all machines in which I run Doom Emacs, not because I expect to build a community around it or anything like that. If you care about using the code after reading this text and you are happy with it, that’s great, but that’s just a plus. I opened the article ranting about Beads’ 300K SLOC codebase, and “bloat” is maybe the biggest concern I have with pure vibecoding. From my limited experience, coding agents tend to take the path of least resistance to adding new features, and most of the time this results in duplicating code left and right. Coding agents rarely think about introducing new abstractions to avoid duplication, or even to move common code into auxiliary functions. They’ll do great if you tell them to make these changes—and profoundly confirm that the refactor is a great idea—but you must look at their changes and think through them to know what to ask. You may not be typing code, but you are still coding in a higher-level sense. But left unattended, you’ll end up with vast amounts of duplication: aka bloat. I fear we are about to see an explosion of slow software like we have never imagined before. And there is also the cynical take: the more bloat there is in the code, the more context and tokens agents need to understand it, so the more you have to pay their providers to keep up with the project. And speaking of open source… we must ponder what this sort of coding process means in this context. I’m worried that vibecoding can lead to a new type of abuse of open source that is hard to imagine: yes, yes, training the AI models has already been done by abusing open source, but that’s nothing compared to what might come in terms of taking over existing projects or drowning them with poor contributions. I’m starting to question my preference for BSD-style licenses all along… and this is such an interesting and important topic that I have more to say, but I’m going to save those thoughts for the next article. Vibecoding has been an interesting experiment. I got exactly what I wanted with almost no effort but it all feels hollow. I’ve traded the joy of building for the speed of prompting, and while the result is useful, it’s still just “slop” to me. I’m glad it works, but I’m worried about what this means for the future of software. Visit ticket and ticket.el to play with these tools if you are curious or need some sort of lightweight ticket management system for your AI interactions.

0 views
Blog System/5 9 months ago

Grumpy Julio plays with CLI coding agents

It’s no secret that I’ve been grumpy about the new AI-based coding trend. I’ve been grumpy about the “push from above to use AI or else”. I’ve been grumpy about the eye-rolling hype I see on LinkedIn. I’ve been grumpy about being on the receiving end of vibe-coded PRs that over-engineer solutions to simple problems. I’ve been grumpy about the thought that we are about to see an amount of bloat like we have never imagined before. But, at the same time, I’ve been using LLMs to review my articles, to perform deep research, to generate cover pictures, and before last week, I had even dipped my toes into AI-based coding agents to help me with boring, repetitive tasks. And you know what? I see their promise of increased productivity, yet the amounts of slop I’ve witnessed make me skeptical and I have had little experience with coding agents myself to judge their promised usefulness. So… surprise! Last weekend I decided to start a Claude Code subscription and, after spending a week on it, I am uncomfortably excited to use it more. How has this happened? Let’s take a look at how I ended here, the kinds of mini-projects I worked on throughout this past week, and the (semi-expected) downsides I encountered. It’s sad to have to say this, but this article was hand-written. Yes, despite the em dashes. Subscribe to show your support! Over the course of last year, I was exposed to multiple vibe-coded PRs and was not impressed. Those PRs came with unnecessary features, code duplication and improper abstractions, useless comments littered throughout, and useless “change-detector” tests. Reviewing these PRs was a lot of effort for me and pushing back on obvious bugs was exhausting. But coding agents are all the rage today and I’m being… let’s say… strongly encouraged to use them. So I dipped my toes in with Gemini CLI for a little bit. (Why not Claude Code? Easy: because it doesn’t offer a free tier whereas Gemini CLI does.) During this early trial period, I restricted myself to relatively simple and boring changes like “fill in these tests” or “help me fix this algorithm that doesn’t quite work”—and it delivered. However, any attempts at asking for more complex changes usually went haywire for me. Now, during the last few weeks, I’ve been rewriting the core interpreter of EndBASIC; all of it by hand. This is the kind of work where I just cannot trust AI (yet?) to generate efficient and minimal code. But, as I approach the “last bits” of the core foundations, what’s left to do is kinda boring. It’s repetitive, but not the kind of code that can be abstracted behind functions. And it’s straightforward once the underpinnings have been figured out. So… after being nudged to use Claude Code over, and over… and over again… I finally gave in and, just a week ago, I decided to pony up and get a Pro subscription to toy with it in my side projects. Confirmation email showing my purchase of the Claude Code Pro subscription. Dipping my toes in nixpkgs Right when I decided to give Claude Code a go, I also decided to try NixOS. The trigger for this was an article on using micro VMs to isolate Claude Code . Installing NixOS was easy but after setting it up, I was missing a couple of packages. This was the perfect opportunity to give Claude Code a “meaty” task for something I was too lazy to do by hand: the nixpkgs language isn’t famous for being easy to work with, and I could live without those packages just fine, but having them around if possible would be “nice to have”. Note that I’m not new to the software packaging world. I spent years creating and maintaining packages for NetBSD and I also managed a couple of RPMs for Fedora. So, even if nixpkgs’ syntax was completely alien to me, I could reason about the semantics of the vibe-coded packages. Consequently, even when Claude Code was really confident about its creations, I knew I had to iterate on them a little. By now I feel like I have some reasonably decent PRs ( one for ticket —more below—and one fo ssh-agent-switcher ) to merge upstream, but as we’ll continue seeing throughout this experience, the human iteration part that followed the initial code dump was critical to obtain high-quality results. Stack of Jujutsu commits showing three pending packages: one for ticket, one for shtk and one for ssh-agent-switcher. Supercharging EndTRACKER I then looked at EndTRACKER—my poorly-named dynamic blog service—and thought… hey, I haven’t touched this project in a long time and there are a few important features and large-scale code changes I’ve been wanting to do in order to make it public. What if I used it as a playground for agenetic coding? I started by asking Claude Code to write a “delete comment” feature for comment moderation. This required implementing a new REST API—a truly boring and tedious thing to do at this point—and figuring out the UI. My first prompt was rather poor in retrospect, but given how many other APIs exist in the code base and the fact that the UI is standard Vue.js, Claude Code pretty much one-shotted the implementation. I had a long-desired feature in my hands in basically minutes. Next, I wanted to do something trickier: I wanted to prune anything that resembled PII from the database. In particular, I wanted to eliminate the literal user agent strings and replace them with more general data points about them (browser / OS pairs). This was not a hard change to do by hand, but it required dealing with a new dependency I was not familiar with, implementing new database hooks, updating business logic, and creating a throw-away migration script. And this is where things got interesting. My first prompt was way too under-specified, but I got back a change that seemed OK. I tried to salvage it with manual iteration but soon concluded that I had to start over. After all, Claude Code spent like 5 minutes creating code so… don’t get too attached to any changes it makes! I wrote a new prompt, this time much more detailed, and clarified various “mistakes” I had seen in the first implementation. At this point, I instructed Claude Code to generate a plan, and at each step during execution, to create a new commit, to update tests, and to run them all. Claude Code churned along for a while and produced about 8 different commits for the various implementation phases. And these 8 commits looked nice: their descriptions made sense, the changes were lint-free, well-formatted, and with good docstrings, and there was new test coverage. But… individually, these separate “small changes” were pointless because the boundaries between them were meaningless. Furthermore, as I started reviewing the diffs in detail and playing with the results, I started encountering deficiencies: unnecessary code and features that I did not ask for, incomplete logic, misplaced and duplicate code… It took about 7 more iterations (and therefore 7 more prompts and commits) to work with Claude Code to come up with a decent change. By then I was pretty happy with the combined result so I squashed all 15 commits into one and shipped the feature. The above is important to highlight though. The original vibe-coded result was not of the quality I would expect. I had to do deep thinking work to simplify the implementation, remove fluff, and to make it efficient (even if the changes were via prompts). And at no point did the 15 commits leave my machine: to an outsider, all I did was write just one PR —but it’d have been trivial for me to inflate numbers at the expense of my reviewer’s time and CI costs if I needed to (hint: be careful with what you measure). So far so good though. This sort of iteration was more interesting than I expected. The really cool bit came soon after when I asked Claude Code to produce a throw-away migration tool to deconstruct the user agents and store their basic data points in separate columns. I gave it access to the test database and… it pretty much one-shotted the tool. As a migration tool, I couldn’t care less about the maintainability of the code because I would delete it immediately after-the-fact, so this was just a perfect use of time. And what was even cooler is that, once I found that the tool was too slow when I ran it on the real dataset, I asked Claude Code to parallelize a specific loop using async primitives and just a couple of minutes later I had an optimized version. Why did I say cooler though? Because if I had written this tool by hand, the trade-off between letting the unoptimized version churn for ~30 minutes vs. spending time to make it parallel and rerun it was not obvious. But with the agent, I had a fixed version in under 2 minutes so I did actually save more than 20 minutes of my time. The next thing I did late last Friday evening was debunk a claim from a peer that implementing an idea I proposed was “the nice solution that would take 6 months to implement”. I suppose I failed to communicate my idea in textual writing because while the proposal could certainly become complicated and a multi-month project, the basic implementation would really be a ~200 SLOC script. And then it hit me… the idea is actually simple. So… why can’t I vibe-code the solution to show it in practice, instead of trying to describe and argue about hypotheticals? And indeed so. I spent about 20 minutes writing a detailed prompt with examples and expected results—aka a mini design doc—and fed it to Claude Code for planning and implementation. And voila: 10 minutes later I had a tangible script to demonstrate what I was proposing. Note that 20 minutes composing an initial prompt is a longer time than I expected coming into this experiment. But as I get more experience communicating intent and getting a feeling for what works and doesn’t, it really does take time to write down desired changes in a way that allows the AI to come up with a reasonably-good solution upfront. Lastly, and during this same time period, I also started using the ticket tool to track tasks for the agent. Now, itself is OK: it’s a trivial tool to manipulate text files that represent tickets. But… as I worked with it more, I was missing some sort of integration with Emacs. So, hey, why not ask the agent to vibe-code an Emacs package for it? I can read LISP but I cannot easily write a plugin from scratch without a significant investment in learning. And you guessed it: the agent gave me a in just a few minutes, and it did exactly what I wanted with zero drama. I had to iterate on it because, while it worked, I wanted more features as I played with the results… but it was awesome to witness that I could build this integration “for free” as I would just not have done it at all otherwise. What can I say. This week’s experiences have left me wanting to use Claude Code more , not less. I’ve done a bunch of things that were just out of reach due to my lack of prerequisite knowledge. I’ve been able to do significant changes that I had postponed for years because those changes were mechanical and not exciting to execute on. The key insight may be that I was able to do all of the above even when my energy was low. This week had been incredibly draining due to a work-related summit so my interest in coding “in the evenings” was just not there. But prompting Claude Code to get started was so frictionless that it was enough to get me started. It really feels like gaining a superpower; and for things that are low stakes or not novel, it’s perfectly fine. But… it’s not all roses. The risks of vibe-coding are even more obvious to me than they were before. Creating convincing slop and gaming productivity metrics by producing more code and more PRs than ever is way too easy—and if those metrics become targets (as will inevitably happen), then slop is what we’ll get. Beware that just because we now can create something doesn’t mean we should : all code comes with significant maintenance costs, and those need to be evaluated. Reflecting back on this experience, it was genuinely difficult to produce solid changes that I was proud of and that didn’t carry performance problems, code duplication, or obvious breakage. I had to review the outcome of the AI various times and slowly iterate on it to turn it into production-grade code. A better initial prompt would have steered the results to a better place, but I’m not convinced the output would have passed my quality bar anyway. I’m not ready to buy into the “let agents loose on a project” trend. I see what these agents produce at scale when left unattended and… I’m terrified. Yes, they generate convincing and functional pieces of software like a web browser , a C++ compiler , or a ticket tracker … but when you start peeking under the covers, you realize that the browser has 3MM lines of code even when it uses Servo (a browser engine!) under the hood; the C++ compiler is slow and unoptimized; and the ticket tracker brings machines to a halt with its 300K SLOC. If we had ever complained about software bloat, we can’t comprehend the amount that’s coming. Anyway. Did I code less during this first week with Claude Code? You know, I’m not sure. I definitely typed less code, but I still had to put in the work to review and adjust it to my liking. So it’s not 100% clear to me that I was more “productive” with the AI than without on a real feature. That said, it’s true that I got more different things done. At the end of the day, coding agents are tools to add to your tool belt, not to wholesale replace it. Who knows, maybe this will change with better models, or maybe we have plateaued. For now, though, I’m excited to play with this stuff more.

0 views
Blog System/5 10 months ago

ssh-agent broken in tmux? I've got you!

A little over two years ago, I wrote an article titled SSH agent forwarding and tmux done right . In it, I described how SSH agent forwarding works—a feature that lets a remote machine use the credentials stored in your local ssh-agent instance—and how using a console multiplexer like tmux or screen often breaks it. In that article, I presented the ssh-agent-switcher : a program I put together in a few hours to fix this problem. In short, ssh-agent-switcher exposes an agent socket at a stable location ( by default) and proxies all incoming credential requests to the transient socket that the sshd server creates on a connection basis. In this article, I want to formalize this project by presenting its first actual release, 1.0.0, and explain what has changed to warrant this release number. I put effort into creating this formal release because ssh-agent-switcher has organically gained more interest than I imagined as it is solving a real problem that various people have. When I first wrote ssh-agent-switcher, I did so to fix a problem I was having at work: we were moving from local developer workstations to remote VMs, we required SSH to work on the remote VMs for GitHub access, and I kept hitting problems with the ssh-agent forwarding feature breaking because I’m an avid user of tmux . To explain the problem to my peers, I wrote the aforementioned article and prototyped ssh-agent-switcher after-hours to demonstrate a solution. At the end of the day, the team took a different route for our remote machines but I kept using this little program on my personal machines. Because of work constraints, I had originally written ssh-agent-switcher in Go and I had used Bazel as its build system. I also used my own shtk library to quickly write a bunch of integration tests and, because of the Bazel requirement, I even wrote my first ruleset, rules_shtk , to make it possible. The program worked, but due to the apparent lack of interest, I considered it “done” and what you found in GitHub was a code dump of a little project I wrote in a couple of free evenings. Recently, however, ssh-agent-switcher stopped working on a Debian testing machine I run and I had to fix it. Luckily, someone had sent a bug report describing what the problem was: OpenSSH 10.1 had changed the location where sshd creates the forwarding sockets and even changed their naming scheme, so ssh-agent-switcher had to adapt. Fixing this issue was straightforward, but doing so made me have to “touch” the ssh-agent-switcher codebase again and I got some interest to tweak it further. My energy to work on side-projects like this one and to write about them comes from your support. Subscribe now to motivate future content! As I wanted to modernize this program, one thing kept rubbing me the wrong way: I had originally forced myself to use Go because of potential work constraints. As these requirements never became relevant and I “needed to write some code” to quench some stress, I decided to rewrite the program in Rust. Why, you ask? Just because I wanted to. It’s my code and I wanted to have fun with it, so I did the rewrite. Which took me into a detour. You see: while command line parsing in Rust CLI apps is a solved problem , I had been using the ancient getopts crate in other projects of mine out of inertia. Using either library requires replicating some boilerplate across apps that I don’t like, so… I ended up cleaning up that “common code” as well and putting it into a new crate aptly-but-oddly-named getoptsargs . Take a look and see if you find it interesting… I might write a separate article on it. Doing this rewrite also made me question the decision to use Bazel (again imposed by constraints that never materialized) for this simple tool: as much as I like the concepts behind this build system and think it’s the right choice for large codebases, it was just too heavy for a trivial program like ssh-agent-switcher. So… I just dropped Bazel and wrote a Makefile—which you’d think isn’t necessary for a pure Rust project but remember that this codebase includes shell tests too. With the Rust rewrite done, I was now on a path to making ssh-agent-switcher a “real project” so the first thing I wanted to fix were the ugly setup instructions from the original code dump. Here is what the project README used to tell you to write into your shell startup scripts: Yikes. You needed shell-specific logic to detach the program from the controlling session so that it didn’t stop running when you logged out, as that would have made ssh-agent-switcher suffer from the exact same problems as regular sshd socket handling. The solution to this was to make ssh-agent-switcher become a daemon on its own with proper logging and “singleton” checking via PID file locking. So now you can reliably start it like this from any shell: I suppose you could make systemd start and manage ssh-agent-switcher automatically with a per-user socket trigger without needing the daemonization support in the binary per se… but I do care about more than just Linux and so assuming the presence of systemd is not an option. With that done, I felt compelled to fix a zero-day TODO that kept causing trouble for people: a fixed-size buffer used to proxy requests between the SSH client and the forwarded agent. This limitation caused connections to stall if the response from the ssh-agent contained more keys than fit in the buffer. The workaround had been to make the fixed-size buffer “big enough”, but that was still insufficient for some outlier cases and came with the assumption that the messages sent over the socket would fit in the OS internal buffers in one go as well. No bueno. Fixing this properly required one of the following: adding threads to handle reads and writes over two sockets in any order, dealing with the annoying / family of system calls, or using an async runtime and library (tokio) to deal with the event-like nature of proxying data between two network connections. People dislike async Rust for some good reasons, but async is the way to get to the real fearless concurrency promise. I did not fancy managing threads by hand, and I did not want to deal with manual event handling… so async it was. And you know what? Switching to async had two immediate benefits: Handling termination signals with proper cleanup became straightforward. The previous code had to install a signal handler and deal with potential races in the face of blocking system calls by doing manual polling of incoming requests, which isn’t good if you like power efficiency. Using tokio made this trivial and in a way that I more easily trust is correct. I could easily implement the connection proxying by using an event-driven loop and not having to reason about threads and their terminating conditions. Funnily enough, after a couple of hours of hacking, I felt proud of the proxying algorithm and the comprehensive unit tests I had written so I asked Gemini for feedback, and… while it told me my code was correct, it also said I could replace it all with a single call to a primitive! Fun times. I still don’t trust AI to write much code for me, but I do like it a lot to perform code reviews. Even with tokio in the picture and all of the recent new features and fixes, the Rust binary of ssh-agent-switcher is still smaller (by 100KB or so) than the equivalent Go one and I trust its implementation more. Knowing that various people had found this project useful over the last two years, I decided to conclude this sprint by creating an actual “formal release” of ssh-agent-switcher. Formal releases require: Documentation, which made me write a manual page . A proper installation process, which made me write a traditional -like script because doesn’t support installing supporting documents. A tag and release number, which many people forget about doing these days but are critical if you want the code to be packaged in upstream OSes. And with that, ssh-agent-switcher 1.0.0 went live on Christmas day of 2025. pkgsrc already has a package for it ; what is your OS waiting for? 😉 In that article, I presented the ssh-agent-switcher : a program I put together in a few hours to fix this problem. In short, ssh-agent-switcher exposes an agent socket at a stable location ( by default) and proxies all incoming credential requests to the transient socket that the sshd server creates on a connection basis. In this article, I want to formalize this project by presenting its first actual release, 1.0.0, and explain what has changed to warrant this release number. I put effort into creating this formal release because ssh-agent-switcher has organically gained more interest than I imagined as it is solving a real problem that various people have. Some background When I first wrote ssh-agent-switcher, I did so to fix a problem I was having at work: we were moving from local developer workstations to remote VMs, we required SSH to work on the remote VMs for GitHub access, and I kept hitting problems with the ssh-agent forwarding feature breaking because I’m an avid user of tmux . To explain the problem to my peers, I wrote the aforementioned article and prototyped ssh-agent-switcher after-hours to demonstrate a solution. At the end of the day, the team took a different route for our remote machines but I kept using this little program on my personal machines. Because of work constraints, I had originally written ssh-agent-switcher in Go and I had used Bazel as its build system. I also used my own shtk library to quickly write a bunch of integration tests and, because of the Bazel requirement, I even wrote my first ruleset, rules_shtk , to make it possible. The program worked, but due to the apparent lack of interest, I considered it “done” and what you found in GitHub was a code dump of a little project I wrote in a couple of free evenings. New OpenSSH naming scheme Recently, however, ssh-agent-switcher stopped working on a Debian testing machine I run and I had to fix it. Luckily, someone had sent a bug report describing what the problem was: OpenSSH 10.1 had changed the location where sshd creates the forwarding sockets and even changed their naming scheme, so ssh-agent-switcher had to adapt. Fixing this issue was straightforward, but doing so made me have to “touch” the ssh-agent-switcher codebase again and I got some interest to tweak it further. My energy to work on side-projects like this one and to write about them comes from your support. Subscribe now to motivate future content! The Rust rewrite As I wanted to modernize this program, one thing kept rubbing me the wrong way: I had originally forced myself to use Go because of potential work constraints. As these requirements never became relevant and I “needed to write some code” to quench some stress, I decided to rewrite the program in Rust. Why, you ask? Just because I wanted to. It’s my code and I wanted to have fun with it, so I did the rewrite. Which took me into a detour. You see: while command line parsing in Rust CLI apps is a solved problem , I had been using the ancient getopts crate in other projects of mine out of inertia. Using either library requires replicating some boilerplate across apps that I don’t like, so… I ended up cleaning up that “common code” as well and putting it into a new crate aptly-but-oddly-named getoptsargs . Take a look and see if you find it interesting… I might write a separate article on it. Doing this rewrite also made me question the decision to use Bazel (again imposed by constraints that never materialized) for this simple tool: as much as I like the concepts behind this build system and think it’s the right choice for large codebases, it was just too heavy for a trivial program like ssh-agent-switcher. So… I just dropped Bazel and wrote a Makefile—which you’d think isn’t necessary for a pure Rust project but remember that this codebase includes shell tests too. Daemonization support With the Rust rewrite done, I was now on a path to making ssh-agent-switcher a “real project” so the first thing I wanted to fix were the ugly setup instructions from the original code dump. Here is what the project README used to tell you to write into your shell startup scripts: Yikes. You needed shell-specific logic to detach the program from the controlling session so that it didn’t stop running when you logged out, as that would have made ssh-agent-switcher suffer from the exact same problems as regular sshd socket handling. The solution to this was to make ssh-agent-switcher become a daemon on its own with proper logging and “singleton” checking via PID file locking. So now you can reliably start it like this from any shell: I suppose you could make systemd start and manage ssh-agent-switcher automatically with a per-user socket trigger without needing the daemonization support in the binary per se… but I do care about more than just Linux and so assuming the presence of systemd is not an option. Going async With that done, I felt compelled to fix a zero-day TODO that kept causing trouble for people: a fixed-size buffer used to proxy requests between the SSH client and the forwarded agent. This limitation caused connections to stall if the response from the ssh-agent contained more keys than fit in the buffer. The workaround had been to make the fixed-size buffer “big enough”, but that was still insufficient for some outlier cases and came with the assumption that the messages sent over the socket would fit in the OS internal buffers in one go as well. No bueno. Fixing this properly required one of the following: adding threads to handle reads and writes over two sockets in any order, dealing with the annoying / family of system calls, or using an async runtime and library (tokio) to deal with the event-like nature of proxying data between two network connections. Handling termination signals with proper cleanup became straightforward. The previous code had to install a signal handler and deal with potential races in the face of blocking system calls by doing manual polling of incoming requests, which isn’t good if you like power efficiency. Using tokio made this trivial and in a way that I more easily trust is correct. I could easily implement the connection proxying by using an event-driven loop and not having to reason about threads and their terminating conditions. Funnily enough, after a couple of hours of hacking, I felt proud of the proxying algorithm and the comprehensive unit tests I had written so I asked Gemini for feedback, and… while it told me my code was correct, it also said I could replace it all with a single call to a primitive! Fun times. I still don’t trust AI to write much code for me, but I do like it a lot to perform code reviews. Documentation, which made me write a manual page . A proper installation process, which made me write a traditional -like script because doesn’t support installing supporting documents. A tag and release number, which many people forget about doing these days but are critical if you want the code to be packaged in upstream OSes.

0 views
Blog System/5 11 months ago

From Azure Functions to FreeBSD

On Thanksgiving morning, I woke up to one of my web services being unavailable. All HTTP requests failed with a “503 Service unavailable” error. I logged into the console, saw a simplistic “Runtime version: Error” message, and was not able to diagnose the problem. I did not spend a lot of time trying to figure the issue out and I didn’t even want to contact the support black hole. Because… there was something else hidden behind an innocent little yellow warning at the top of the dashboard: Migrate your app to Flex Consumption as Linux Consumption will reach EOL on September 30 2028 and will no longer be supported. I had known for a few weeks now, while trying to set up a new app, that all of my Azure Functions apps were on death row. The free plan I was using was going to be decommissioned and the alternatives I tried didn’t seem to support custom handlers written in Rust. I still had three years to deal with this, but hitting a showstopper error pushed me to take action. All of my web services are now hosted by the FreeBSD server in my garage with just a few tweaks to their codebase. This is their migration story. Blog System/5 and the open source projects described below are all made in my limited free time. Subscribe now to show your support; it goes a long way! Back in 2021, I had been developing my EndBASIC language for over a year and I wanted to create a file sharing service for it. Part of this was to satisfy my users, but another part was to force myself into the web services world as I felt “behind”. At that time, I had also been at Microsoft for a few months already working on Azure Storage. One of the perks of the job was something like $300 of yearly credit to deploy stuff on Azure for learning purposes. It was only “natural” that I’d pick Azure for what I wanted to do with EndBASIC. Now… $300 can be plentiful for a simple app, but it can also be paltry. Running a dedicated VM would eat through this in a couple of months, but the serverless model offered by Azure Functions with its “infinite” free tier would go a long way. I looked at their online documentation, found a very good guide on how to deploy Rust-native functions onto a Linux runtime , and… I was sold. I quickly got a bare bones service up and running on Azure Functions and I built it up from there. Based on these foundations, I later developed a separate service for my own site analytics (poorly named EndTRACKER ), and I recently started working on a new service to provide secure auto-unlock of encrypted ZFS volumes (stay tuned!). And, for the most part, the experience with Azure has been neat. I learned a bunch and I got to a point where I had set up “push on green” via GitHub Actions and dual staging vs. prod deployments. The apps ran completely on their own for the last three years, a testament to the stability of the platform and to the value of designing for testability . Until now that is. Compute-wise, I was set: Azure Functions worked fine as the runtime for my apps’ logic and it cost pennies to run, so the $300 was almost untouched. But web services aren’t made of compute alone: they need to store data, which means they need a database. My initial research in 2021 concluded that the only option for a database instance with a free plan was to go with, no surprise, serverless Microsoft SQL Server (MSSQL). I had never used Microsoft’s offering but it couldn’t be that different from PostgreSQL or MySQL, could it? Maybe so, but I didn’t get very far in that line of research. The very first blocker I hit was that the MSSQL connection required TLS and this hadn’t been implemented in the connector I chose to use for my Rust-based functions. I wasted two weeks implementing TLS support in (see PR #1200 and PR #1203 ) and got it to work, but that code was not accepted upstream because it conflicted with their business strategy. Needless to say, this was disappointing because getting that to work was a frigging nightmare. In any case, once I passed that point, I started discovering more missing features and bugs in the MSSQL connector, and then I also found some really weird surprises in MSSQL’s dialect of SQL. TL;DR, this turned into a dead end. On the left, the default instance and cost selected by Azure when choosing to create a managed PostgreSQL server today. On the right, minimum possible cost after dialing down CPU, RAM, disk, and availability requirements. I had no choice other than to provision a full PostgreSQL server on Azure. Their onboarding wizard tried to push me towards a pretty beefy and redundant instance that would cost over $600 per month when all I needed was the lowest machine you could get for the amount of traffic I expected. Those options were hidden under a “for development only” panel and riddled with warnings about no redundancy, but after I dialed all the settings down and accepted the “serious risks”, I was left with an instance that’d cost $15 per month or so. This fit well well within the free yearly credit I had access to, so that was it. About two months ago, I started working on a new service to securely auto-unlock ZFS encrypted volumes (more details coming). For this, I had to create a new Azure Functions deployment… and I started seeing the writing on the wall. I don’t remember the exact details, but it was really difficult to get the creation wizard to provision me the same flex plan I had used for my other services, and it was warning me that the selected plan was going to be axed in 2028. At the time of this writing, 2028 is still three years out and this warning was for a new service I was creating. I didn’t want to consider migrating neither EndBASIC nor EndTRACKER to something else just yet. Until Thanksgiving, that was. On Thanksgiving morning, I noticed that my web analytics had stopped working. All HTTP API requests failed with a “503 Service unavailable.” error but, interestingly, the cron-triggered APIs were still running in the background just fine and the staging deployment slot of the same app worked fine end-to-end as well. I tried redeploying the app with a fresh binary, thinking that a refresh would fix the problem, but that was of no use. I also poked through the dashboard trying to figure out what “Runtime version: Error” would be about, making sure the version spec in was up-to-date, and couldn’t figure it out either. Summary state of my problematic Azure Functions deployment. Note the cryptic runtime error along with the subtle warning at the top about upcoming deprecations. So… I had to get out of Azure Functions, quick. Not accidentally, I had bought a second-hand, over-provisioned ThinkStation (2x36-core Xeon E5-2697, 64 GB of RAM, a 2 TB NVMe drive, and a 4x4 TB HDD array) just two years back. The justification I gave myself was to use it as my development server, but I had this idea in the back of my mind to use it to host my own services at some point. The time to put it to serving real-world traffic with FreeBSD 14.x had come. The way you run a serverless Rust (or Go) service on Azure Functions is by creating a binary that exposes an HTTP server on the port provided to it by the environment variable. Then, you package the binary along a set of metadata JSON files that tell the runtime what HTTP routes the binary serves and push the packaged ZIP file to Azure. From there on, the Azure Functions runtime handles TLS termination for those routes, spawns your binary server on a micro VM on demand, and redirects the requests to it. By removing the Azure Functions runtime from the picture, I had to make my server binary stand alone. This was actually pretty simple because the binary was already an HTTP server: it just had to be coerced into playing nicely with FreeBSD’s approach to running services. In particular, I had to: Inject configuration variables into the server process at startup time. These used to come from the Azure Functions configuration page, and are necessary to tell the server where the database lives and what credentials to use. Make the service run as an unprivileged user, easily. Create a PID file to track the execution of the process so that the framework could handle restarts and stop requests. Store the logs that the service emits via stderr to a log file, and rotate the log to prevent local disk overruns. Most daemons implement all of the above as features in their own code, but I did not want to have to retrofit all of these into my existing HTTP service in a rush. Fortunately, FreeBSD provides this little tool, daemon(8) , which wraps an existing binary and offers all of the above. This incantation was enough to get me going: I won’t dive into the details of each flag, but to note: specifies which PID file to create; specifies where to store the stdout and stderr of the process; is required for log rotation (much more below); drops privileges to the given user; and specifies the “title” of the process to display in output. The trick was sufficient to inject configuration variables upon process startup, simulating the same environment that my server used to see when spawned by the Azure Functions runtime. Hooking that up into an service script was then trivial: And with that: Ta-da! I had the service running locally and listening to a local port determined in the configuration file. As part of the migration out of Azure Functions, I switched to self-hosting PostgreSQL as well. This was straightforward but required a couple of extra improvements to my web framework: one to stop using a remote PostgreSQL instance for tests (something I should have done eons ago), and another to support local peer authentication to avoid unnecessary passwords. In the call to above, I briefly mentioned the need for the flag to support log rotation. What’s that about? You see, in Unix-like systems, when a process opens a file, the process holds a handle to the open file. If you delete or rename the file, the handle continues to exist exactly as it was . This has two consequences: If you rename the file, all subsequent reads and writes go to the new file location, not the old one. If you delete the file, all subsequent reads and writes continue to go to disk but to a file you cannot reference anymore. You can run out of disk space and, while will confirm the fact, will not let you find what file is actually consuming it! For a long-running daemon that spits out verbose logs, writing them to a file can become problematic because you can end up running out of disk space. To solve this problem, daemons typically implement log rotation : a mechanism to keep log sizes in check by moving them aside when a certain period of time passes or when they cross a size threshold, and then only keeping the last N files around. Peeking into one of the many examples in my server, note how is the “live” log where writes go to but there is a daily archive for up to a week: Having all daemons implement log rotation logic on their own would be suboptimal because you’d have duplicate logic throughout the system and you would not be able to configure policy easily for them all. This is where newsyslog(8) on FreeBSD (or on Linux) comes into play. is a tool that rotates log files based on criteria such as size or time and optionally compresses them. But remember: the semantics of open file handles mean that simply renaming log files is insufficient! Once takes action and moves a log file aside, it must ensure that the process that was writing to that file closes the file handle and reopens it so that writes start going to the new place. This is typically done via sending a to the daemon, and is why we need to pass to the call. To illustrate the sequence: The system starts a service via and redirects logs to . runs and determines that needs to be rotated because a day has passed. renames to and creates a new and empty . At this point is still writing to ! sends a to the process. The process closes its file handle for the log, reopens (which is the fresh new log file), and resumes writing. compresses the file for archival now that it’s quiesced. Configuring is easy, but cryptic. We can create a service-specific configuration file under that provides entries for our service, such as: I’ll leave you to the manpage to figure out what the magic is (but in short, it controls retention count, rotation schedule, and compression). As I briefly mentioned earlier, the Azure Functions runtime was responsible for TLS termination in my previous setup. Without such a runtime in place, I had to configure TLS on my own in my HTTP server… or did I? I had been meaning to play with Cloudflare Tunnels for a while given that I already use Cloudflare for DNS. Zero Trust Tunnels allow you to expose a service without opening inbound ports in your firewall. The way this works is by installing the tunnel daemon on your machine and configuring the tunnel to redirect certain URL routes to an internal address (typically ). Cloudflare then acts as the frontend for the requests, handles TLS termination and DDOS protection, and then redirects the request to your local service. Interactions between client machines, Cloudflare servers, the cloudflared tunnel agent, and the actual HTTP servers I wrote. The obvious downside of relying on someone else to do TLS termination instead of doing it yourself on your own server is that they can intercept and modify your traffic. For the kinds of services I run this isn’t a big deal for me, and the simplicity of others dealing with certificates is well welcome. Note that I was already offloading TLS termination to Azure Functions anyway, so this isn’t a downgrade in security or privacy. But using Cloudflare as the frontend came with a little annoyance: CORS handling. You see: the services I run require configuring extra allowed origins, and as soon as I tried to connect to them via the Cloudflare tunnel, I’d get the dreaded “405 Method not allowed” error in the requests. Before, I used to configure CORS orgins from the Azure Functions console, but no amount of peeking through the Cloudflare console showed me how to do this for my tunneled routes. At some point during the investigation, I assumed that I had to configure CORS on my own server. I’m not sure how I reached that bogus conclusion, but I ended up wasting a few hours implementing a configuration system for CORS in my web framework . Nice addition… but ultimately useless. I had not accounted for the fact that because Cloudflare acts as the frontend for the services, it is the one responsible for handling the pre-flight HTTP requests necessary for CORS. In turn, this means that Cloudflare is where CORS needs to be configured but there is nothing “obvious” about configuring CORS in the Cloudflare portal. AI to the rescue! As skeptical as I am of these tools, it’s true that they work well to get answers to common problems—and figuring out how to deal with CORS in Cloudflare was no exception. They told me to configure a transformation rule that explicitly sets CORS response headers for specific subdomains, and that did the trick: Sample rule configuration on the Cloudflare portal to rewrite CORS response headers. Even though AI was correct in this case, the whole thing looked fishy to me, so I did spend time reading about the inner workings of CORS to make sure I understood what this proposed solution was about and to gain my own confidence that it was correct. By now, my web services are now fully running on my FreeBSD machine. The above may have seemed complicated, but in reality it was all just a few hours of work on Thanksgiving morning. Let’s conclude by analyzing the results of the transition. On the plus side, here is what I’ve gained: Predictability: Running in the cloud puts you at the mercy of the upgrade and product discontinuation treadmill of big cloud providers. It’s no fun to have to be paying attention to deprecation messages and adjust to changes no matter how long the deadlines are. FreeBSD also evolves, of course, but it has remained pretty much the same over the last 30 years and I have no reason to believe it’ll significantly change in the years to come. Performance: My apps are so much faster now it’s ridiculous. The serverless runtime of Azure Functions starts quickly for sure, but it just can’t beat a server that’s continuously running and that has hot caches at all layers. That said, I bet the real difference in performance for my use case comes from collocating the app servers with the database, duh. Ease of management: In the past, having automated deployments via GitHub Actions to Azure Functions was pretty cool, not gonna lie. But… being now able to deploy with a trivial , perform administration PostgreSQL tasks with just a , and inspecting logs trivially and quickly by looking at beats any sort of online UI and distributed system. “Doesn’t scale” you say, but it scales up my time . Cost: My Azure bill has gone from $20/month, the majority of which was going into the managed PostgreSQL instance, to almost zero. Yes, the server I’m running in the garage is probably costing me the same or more in electricity, but I was running it anyway already for other reasons. And here is what I’ve lost (for now): Availability (and redundancy): The cloud gives you the chance of very high availability by providing access to multiple regions. Leveraging these extra availability features is not cheap and often requires extra work, and I wasn’t taking advantage of them in my previous setup. So, I haven’t really decreased redundancy, but it’s funny that the day right after I finished the migration, I lost power for about 2 hours. Hah, I think I hadn’t suffered any outages with Azure other than the one described in this article. A staging deployment: In my previous setup, I had dual prod and staging deployments (via Azure Functions slots and separate PostgreSQL databases—not servers) and it was cool to deploy first to staging, perform some manual validations, and then promote the deployment to prod. In practice, this was rather annoying because the deployment flow was very slow and not fully automated (see “manual testing”), but it indeed saved me from breaking prod a few times. Auto-deployments: Lastly and also in my previous setup, I had automated the push to staging and prod by simply updating tags in the GitHub repository. Once again, this was convenient, but the biggest benefit of it all was that the prod build process was “containerized” and not subject to environmental interference. I’d very well set up a cron job or webhook-triggered local service that rebuilt and deployed my services on push… but it’s now hard to beat the simplicity of . None of the above losses are inherent to self-hosting, of course. I could provide alternatives for them all and at some point I will; consider them to-dos! On Thanksgiving morning, I woke up to one of my web services being unavailable. All HTTP requests failed with a “503 Service unavailable” error. I logged into the console, saw a simplistic “Runtime version: Error” message, and was not able to diagnose the problem. I did not spend a lot of time trying to figure the issue out and I didn’t even want to contact the support black hole. Because… there was something else hidden behind an innocent little yellow warning at the top of the dashboard: Migrate your app to Flex Consumption as Linux Consumption will reach EOL on September 30 2028 and will no longer be supported. I had known for a few weeks now, while trying to set up a new app, that all of my Azure Functions apps were on death row. The free plan I was using was going to be decommissioned and the alternatives I tried didn’t seem to support custom handlers written in Rust. I still had three years to deal with this, but hitting a showstopper error pushed me to take action. All of my web services are now hosted by the FreeBSD server in my garage with just a few tweaks to their codebase. This is their migration story. Blog System/5 and the open source projects described below are all made in my limited free time. Subscribe now to show your support; it goes a long way! How did I get here? Back in 2021, I had been developing my EndBASIC language for over a year and I wanted to create a file sharing service for it. Part of this was to satisfy my users, but another part was to force myself into the web services world as I felt “behind”. At that time, I had also been at Microsoft for a few months already working on Azure Storage. One of the perks of the job was something like $300 of yearly credit to deploy stuff on Azure for learning purposes. It was only “natural” that I’d pick Azure for what I wanted to do with EndBASIC. Now… $300 can be plentiful for a simple app, but it can also be paltry. Running a dedicated VM would eat through this in a couple of months, but the serverless model offered by Azure Functions with its “infinite” free tier would go a long way. I looked at their online documentation, found a very good guide on how to deploy Rust-native functions onto a Linux runtime , and… I was sold. I quickly got a bare bones service up and running on Azure Functions and I built it up from there. Based on these foundations, I later developed a separate service for my own site analytics (poorly named EndTRACKER ), and I recently started working on a new service to provide secure auto-unlock of encrypted ZFS volumes (stay tuned!). And, for the most part, the experience with Azure has been neat. I learned a bunch and I got to a point where I had set up “push on green” via GitHub Actions and dual staging vs. prod deployments. The apps ran completely on their own for the last three years, a testament to the stability of the platform and to the value of designing for testability . Until now that is. The cloud database Compute-wise, I was set: Azure Functions worked fine as the runtime for my apps’ logic and it cost pennies to run, so the $300 was almost untouched. But web services aren’t made of compute alone: they need to store data, which means they need a database. My initial research in 2021 concluded that the only option for a database instance with a free plan was to go with, no surprise, serverless Microsoft SQL Server (MSSQL). I had never used Microsoft’s offering but it couldn’t be that different from PostgreSQL or MySQL, could it? Maybe so, but I didn’t get very far in that line of research. The very first blocker I hit was that the MSSQL connection required TLS and this hadn’t been implemented in the connector I chose to use for my Rust-based functions. I wasted two weeks implementing TLS support in (see PR #1200 and PR #1203 ) and got it to work, but that code was not accepted upstream because it conflicted with their business strategy. Needless to say, this was disappointing because getting that to work was a frigging nightmare. In any case, once I passed that point, I started discovering more missing features and bugs in the MSSQL connector, and then I also found some really weird surprises in MSSQL’s dialect of SQL. TL;DR, this turned into a dead end. On the left, the default instance and cost selected by Azure when choosing to create a managed PostgreSQL server today. On the right, minimum possible cost after dialing down CPU, RAM, disk, and availability requirements. I had no choice other than to provision a full PostgreSQL server on Azure. Their onboarding wizard tried to push me towards a pretty beefy and redundant instance that would cost over $600 per month when all I needed was the lowest machine you could get for the amount of traffic I expected. Those options were hidden under a “for development only” panel and riddled with warnings about no redundancy, but after I dialed all the settings down and accepted the “serious risks”, I was left with an instance that’d cost $15 per month or so. This fit well well within the free yearly credit I had access to, so that was it. The outage and trigger About two months ago, I started working on a new service to securely auto-unlock ZFS encrypted volumes (more details coming). For this, I had to create a new Azure Functions deployment… and I started seeing the writing on the wall. I don’t remember the exact details, but it was really difficult to get the creation wizard to provision me the same flex plan I had used for my other services, and it was warning me that the selected plan was going to be axed in 2028. At the time of this writing, 2028 is still three years out and this warning was for a new service I was creating. I didn’t want to consider migrating neither EndBASIC nor EndTRACKER to something else just yet. Until Thanksgiving, that was. On Thanksgiving morning, I noticed that my web analytics had stopped working. All HTTP API requests failed with a “503 Service unavailable.” error but, interestingly, the cron-triggered APIs were still running in the background just fine and the staging deployment slot of the same app worked fine end-to-end as well. I tried redeploying the app with a fresh binary, thinking that a refresh would fix the problem, but that was of no use. I also poked through the dashboard trying to figure out what “Runtime version: Error” would be about, making sure the version spec in was up-to-date, and couldn’t figure it out either. Summary state of my problematic Azure Functions deployment. Note the cryptic runtime error along with the subtle warning at the top about upcoming deprecations. So… I had to get out of Azure Functions, quick. Not accidentally, I had bought a second-hand, over-provisioned ThinkStation (2x36-core Xeon E5-2697, 64 GB of RAM, a 2 TB NVMe drive, and a 4x4 TB HDD array) just two years back. The justification I gave myself was to use it as my development server, but I had this idea in the back of my mind to use it to host my own services at some point. The time to put it to serving real-world traffic with FreeBSD 14.x had come. From serverless to serverful The way you run a serverless Rust (or Go) service on Azure Functions is by creating a binary that exposes an HTTP server on the port provided to it by the environment variable. Then, you package the binary along a set of metadata JSON files that tell the runtime what HTTP routes the binary serves and push the packaged ZIP file to Azure. From there on, the Azure Functions runtime handles TLS termination for those routes, spawns your binary server on a micro VM on demand, and redirects the requests to it. By removing the Azure Functions runtime from the picture, I had to make my server binary stand alone. This was actually pretty simple because the binary was already an HTTP server: it just had to be coerced into playing nicely with FreeBSD’s approach to running services. In particular, I had to: Inject configuration variables into the server process at startup time. These used to come from the Azure Functions configuration page, and are necessary to tell the server where the database lives and what credentials to use. Make the service run as an unprivileged user, easily. Create a PID file to track the execution of the process so that the framework could handle restarts and stop requests. Store the logs that the service emits via stderr to a log file, and rotate the log to prevent local disk overruns. If you rename the file, all subsequent reads and writes go to the new file location, not the old one. If you delete the file, all subsequent reads and writes continue to go to disk but to a file you cannot reference anymore. You can run out of disk space and, while will confirm the fact, will not let you find what file is actually consuming it! The system starts a service via and redirects logs to . runs and determines that needs to be rotated because a day has passed. renames to and creates a new and empty . At this point is still writing to ! sends a to the process. The process closes its file handle for the log, reopens (which is the fresh new log file), and resumes writing. compresses the file for archival now that it’s quiesced. Interactions between client machines, Cloudflare servers, the cloudflared tunnel agent, and the actual HTTP servers I wrote. The obvious downside of relying on someone else to do TLS termination instead of doing it yourself on your own server is that they can intercept and modify your traffic. For the kinds of services I run this isn’t a big deal for me, and the simplicity of others dealing with certificates is well welcome. Note that I was already offloading TLS termination to Azure Functions anyway, so this isn’t a downgrade in security or privacy. CORS But using Cloudflare as the frontend came with a little annoyance: CORS handling. You see: the services I run require configuring extra allowed origins, and as soon as I tried to connect to them via the Cloudflare tunnel, I’d get the dreaded “405 Method not allowed” error in the requests. Before, I used to configure CORS orgins from the Azure Functions console, but no amount of peeking through the Cloudflare console showed me how to do this for my tunneled routes. At some point during the investigation, I assumed that I had to configure CORS on my own server. I’m not sure how I reached that bogus conclusion, but I ended up wasting a few hours implementing a configuration system for CORS in my web framework . Nice addition… but ultimately useless. I had not accounted for the fact that because Cloudflare acts as the frontend for the services, it is the one responsible for handling the pre-flight HTTP requests necessary for CORS. In turn, this means that Cloudflare is where CORS needs to be configured but there is nothing “obvious” about configuring CORS in the Cloudflare portal. AI to the rescue! As skeptical as I am of these tools, it’s true that they work well to get answers to common problems—and figuring out how to deal with CORS in Cloudflare was no exception. They told me to configure a transformation rule that explicitly sets CORS response headers for specific subdomains, and that did the trick: Sample rule configuration on the Cloudflare portal to rewrite CORS response headers. Even though AI was correct in this case, the whole thing looked fishy to me, so I did spend time reading about the inner workings of CORS to make sure I understood what this proposed solution was about and to gain my own confidence that it was correct. Results of the transition By now, my web services are now fully running on my FreeBSD machine. The above may have seemed complicated, but in reality it was all just a few hours of work on Thanksgiving morning. Let’s conclude by analyzing the results of the transition. On the plus side, here is what I’ve gained: Predictability: Running in the cloud puts you at the mercy of the upgrade and product discontinuation treadmill of big cloud providers. It’s no fun to have to be paying attention to deprecation messages and adjust to changes no matter how long the deadlines are. FreeBSD also evolves, of course, but it has remained pretty much the same over the last 30 years and I have no reason to believe it’ll significantly change in the years to come. Performance: My apps are so much faster now it’s ridiculous. The serverless runtime of Azure Functions starts quickly for sure, but it just can’t beat a server that’s continuously running and that has hot caches at all layers. That said, I bet the real difference in performance for my use case comes from collocating the app servers with the database, duh. Ease of management: In the past, having automated deployments via GitHub Actions to Azure Functions was pretty cool, not gonna lie. But… being now able to deploy with a trivial , perform administration PostgreSQL tasks with just a , and inspecting logs trivially and quickly by looking at beats any sort of online UI and distributed system. “Doesn’t scale” you say, but it scales up my time . Cost: My Azure bill has gone from $20/month, the majority of which was going into the managed PostgreSQL instance, to almost zero. Yes, the server I’m running in the garage is probably costing me the same or more in electricity, but I was running it anyway already for other reasons. Availability (and redundancy): The cloud gives you the chance of very high availability by providing access to multiple regions. Leveraging these extra availability features is not cheap and often requires extra work, and I wasn’t taking advantage of them in my previous setup. So, I haven’t really decreased redundancy, but it’s funny that the day right after I finished the migration, I lost power for about 2 hours. Hah, I think I hadn’t suffered any outages with Azure other than the one described in this article. A staging deployment: In my previous setup, I had dual prod and staging deployments (via Azure Functions slots and separate PostgreSQL databases—not servers) and it was cool to deploy first to staging, perform some manual validations, and then promote the deployment to prod. In practice, this was rather annoying because the deployment flow was very slow and not fully automated (see “manual testing”), but it indeed saved me from breaking prod a few times. Auto-deployments: Lastly and also in my previous setup, I had automated the push to staging and prod by simply updating tags in the GitHub repository. Once again, this was convenient, but the biggest benefit of it all was that the prod build process was “containerized” and not subject to environmental interference. I’d very well set up a cron job or webhook-triggered local service that rebuilt and deployed my services on push… but it’s now hard to beat the simplicity of .

0 views
Blog System/5 11 months ago

BazelCon 2025 recap

It has been just over two years since I started Blog System/5, and that means it’s time for the now-usual(?) BazelCon 2025 trip report! The conference, arranged by the Linux Foundation, took place in Atlanta, GA, USA over three days: one for tutorials and two for the main talks. An extra hackathon day, organized by Aspect Build, followed. Unfortunately, a canceled flight meant I missed the tutorials, but I attended the rest of the events. As usual, it was a super-fun time to connect with old acquaintances and an energizing event that left me with plenty of new topics to research. What follows is not a complete summary of the conference, as there were many talks I did not attend and conversations I missed. If you want the full firehose of videos, see the BazelCon 2025 YouTube playlist . And if you want a TL;DR… I’d pick the following highlights: The ecosystem is maturing with becoming mandatory and the BUILD Foundation being a reality in the near horizon. Performance remains a key focus of the Bazel core team and the community, with innovative approaches like Skycache for client-side speed, sophisticated RE improvements for backend efficiency, and new rulesets like that focus on build speed. Community tooling is expanding Bazel’s scope, with projects like Aspect’s task runner aiming to solve long-standing workflow gaps. But the above is just tiny peek into the conference. So, strap your seat belts and let’s dive into the conference. If you want more Bazel content (and much more than that), make sure to click subscribe and support Blog System/5! Google opened by emphasizing their commitment to Bazel, highlighting its growing internal adoption. Their reasoning is that Bazel improves security and hermeticity, in addition to the usual benefits of faster builds and easier open-sourcing of code. This statement seems to be a response to last year’s proposal to create a non-Google Bazel Foundation, which would act as a “backup plan” should Google ever withdraw from the project. Google provided two examples of its growing Bazel adoption. The first is Quantum AI , primarily written in Python and Rust, which saw an 80% reduction in CI time after a migration to Bazel that was driven by just one SWE. The second is their Google Distributed Cloud (GDC) , a version of their cloud product that can run on-premise and in air-gapped instances. The GDC codebase weighs 2.6 GB, is developed by 1,300 engineers, and produces 600 GB of release artifacts. I have to question if the latter is a number to be proud of: when does this madness in bloat stop? The introduction concluded with a few statistics: Bazel’s Slack channel has grown by 18% from the previous year to 8,500 users; there are about 10,800 repos on GitHub with files; and there are about 120,000 files on GitHub. The next session was the customary round of community updates, presented by Jay Conrod from EngFlow and Alex Eagle from Aspect Build. Here are the highlights: Training day: There were six different sessions on the Sunday before the conference, and EngFlow is leading training efforts worldwide. Gazelle: C++ support is on the way for this tool. Version 2.0 will simplify the extensions interface and improve performance. BCR Mirror: Cloudflare is now hosting a mirror for the Bazel Central Registry (BCR). You can use it with Bazel 8.4+ by adding to your configuration—and this will become a default in a future release. Documentation: The most common complaint in community surveys remains the documentation and the steep learning curve. To address this, the BCR website now features icons for sponsorship requests, deprecation notices, and provenance attestations. Furthermore, the Starlark documentation has been published and is now easier to read. In a move to empower the community, the documentation has been migrated out of Google’s internal infrastructure and is available at https://preview.bazel.build/ BUILD Foundation: The foundation currently has three founding members (Spotify, Uber, and Canva) and is looking for four more. The initial meeting is scheduled for December 4th. More on this in its own section. Bzlmod was also a significant topic in this talk, but since it was covered at length in other presentations as well, I have dedicated a separate section to it below. As is tradition, the next session was the State of the Union talk, led by John Field and Tobias Werth from Google. Here are some of the highlights from the update: Local remote repo caching: This new feature is intended to allow the caching of repository rules across different workspaces. Experimental WASM support: There is experimental support for WASM tools in repo rules to enable platform-independent tooling, but its future is still uncertain. Performance improvements: Changes to can save up to 20% of memory. Optimizations in Merkle tree handling can reduce wall time by up to 30%. Analysis phase caching is coming soon (see the “Skycache” section below for more details). There are ongoing efforts to cap disk usage. Path stripping, a feature announced last year, is now more mature and integrated with more rule sets, offering up to an 84% reduction in build time. Analysis time on flag changes has been reduced. Java improvements: Caching has been improved, and method signature changes no longer affect downstream header builds. Starlark flags: A new scoping API is available for Starlark flags. : A new file is being introduced to provide a canonical place for project owners to map targets to flags. More details on its own section. Starlarkification: This effort is almost complete. All rules are now decoupled, with the exception of a few integration points for C++. As of Bazel 9, autoloading of rules is disabled, which means users must now explicitly all the rules they use. Starlark type system: Type annotations and type-checking are coming to Starlark. The syntax will be supported in Bazel 9, with type-checking planned for Bazel 10. The syntax aims for compatibility with Python 3 types, which introduces some limitations on what can be expressed. JetBrains Bazel plugin: The JetBrains-owned Bazel plugin has reached general availability, making the Google-owned plugin a legacy tool. This new plugin promises a much-improved user experience, as it is faster and better integrates the Bazel build graph with IntelliJ’s native understanding of the project structure, avoiding expensive “sync” steps. Internal APIs: There is ongoing work to separate core logic from service interactions (such as remote builds and file system operations), which sounds very similar to how Buck 2 was designed from the start. Much like the community updates talk, this one also opened with bzlmod. Let’s dive into that topic next. The workspace is dead; long live bzlmod! With Bazel 9, support for old-style workspaces has been removed, and given that the vast majority of rulesets now support bzlmod, it’s time for everyone to complete their migration. This is a positive development because bzlmod, through the Bazel Central Registry (BCR) , simplifies rule discovery, project dependencies, and version conflict resolution. Interestingly, but not surprisingly, bzlmod and the BCR have effectively become a package manager for C++. But it’s not all roses. The bzlmod migration has been a significant source of friction for the community due to the intrusive and difficult nature of the change. If you haven’t completed the transition, you can no longer upgrade to newer Bazel versions. The official documentation has also been subpar (which is not surprising), although a great set of articles from EngFlow is now available to clarify the migration process in great detail. To assist with the migration, an automated migration tool is now available, and various people have reported success using AI tools to help with the transition. In a related development, there is now a Maintainer Community Program (MCP) for the BCR. One major pain point I have faced, and one that seems to affect many others, is the tendency of the Bazel ecosystem to couple rule versions with library versions. For example, if you are using an old version of with an equally old version of that is not compatible with bzlmod, you must upgrade to migrate. However, this in turn forces you to upgrade itself. Updating a library can introduce API incompatibilities and behavioral changes, making the upgrade to bzlmod and subsequent major Bazel releases much more difficult than it needs to be. Before we dive into remote execution, let me clarify some terminology. Remote Execution is abbreviated as RE, not RBE. RBE was Google’s now-discontinued cloud product for RE. While the terms are often used interchangeably today (even on Bazel’s own website), it’s a good idea to stick to RE. Similarly, avoid using the term “build farm” as there is a specific RE implementation named Buildfarm . Remote execution is always a hot topic at BazelCon, and for good reason. One of Bazel’s biggest selling points is the performance boost from distributing builds across multiple machines, and nearly every Bazel-related startup offers some form of remote execution solution. In the first RE-focused talk, Son Luong Ngoc from BuildBuddy explained how their product routes actions to maximize performance and minimize execution latency. The talk began with a clear premise: remote builds are spiky and hard to binpack, so how can they be scheduled efficiently for both performance and cost? Here are some of the key features of their RE implementation: Executor types: BuildBuddy provides both managed (OCI, Firecracker, macOS) and self-hosted (Docker, Windows, GPU, and more) executors, each with different performance, isolation, and cost characteristics. Multiple action queues: Executors are organized into pools, and actions can specify which pool they should run on. When an action is received, the scheduler enqueues it in up to three different executors to minimize tail latency, based on the Sparrow scheduler research paper . Work stealing: Dynamic scaling of executor pools is critical for handling spiky build workloads while keeping costs down. To make this more efficient, BuildBuddy allows new executors to steal work from existing ones, which helps redistribute the load. Action merging: This feature coalesces multiple execution requests for the same action into a single execution. As we learned, this can be problematic if a misbehaving executor stalls multiple clients (e.g., several CI jobs). To address this, BuildBuddy speculatively re-executes a running action on a different executor after a certain threshold has passed. Action cancellation: When a user presses Ctrl+C, they are likely to modify code and restart the build, so continuing to run in-flight actions is wasteful. For greater efficiency, BuildBuddy catches the finished event from the BEP and attempts to cancel all remotely-queued actions. Binpacking: Different actions have different resource requirements, and it can be difficult to manually assign them to the right pool and executor. BuildBuddy automatically profiles executed actions (for metrics like peak memory and CPU consumption) and stores this information in the field of the action result, which is then stored on the server. The scheduler uses these details to route actions more effectively. Cold starts: Executing remote actions is similar to running lambda functions: a worker must be started, a container image fetched, and the action executed. To optimize this, BuildBuddy uses affinity routing, where a key is computed based on the primary output name (which is unique for each action) to extract platform, target, and output details. This allows similar actions to be routed to similar executors. Recycled runners: Some customers need to maintain heavyweight processes on the remote worker, such as test databases or the Docker daemon. While not hermetic, this is often desirable for high-performance scenarios. The use of these features is customized through execution properties. Custom resources: Some actions may require access to specialized resources like GPUs, FPGAs, or simulators. For better binpacking, customers can define the “size” of different executor types and annotate actions with the resources they consume. Fair scheduling: With multi-tenancy, users can set a “priority” for the actions of a build using the flag. A common use case is to define three priority bands: interactive builds, CI, and cron jobs. The BuildBuddy scheduler takes this property into account. After detailing these existing features, the talk concluded with a glimpse into the future: extending the RE protocol with a remote build graph API. The current protocol is very chatty, making it difficult to colocate actions (such as a compile-link-test chain). A protocol that understands action relationships could significantly improve this. This talk left me wondering which of these features are also offered by other major RE vendors and open-source implementations. I briefly chatted with the EngFlow folks at the conference and they told me they have most of these too; it’d be nice to have a comparison chart among vendors and free solutions. The next major topic for RE was cost savings and reliability, which was covered in at least two talks. The first talk, presented by Rahul Roy from Glean, focused on how their adoption of Buildbarn for scalability unexpectedly doubled their CI costs. The primary causes for this increase were an up-to-20% per-action overhead in the Buildbarn worker and a lack of Bazel client caching in their GitHub Actions runners. To solve these issues, they chose to adopt spot instances in their deployment of Buildbarn on GCP’s Kubernetes offering, but this is not as easy as it seems: The default Kubernetes autoscaler relies on CPU and memory utilization for its decisions, but these metrics are poor predictors of CI traffic patterns. Action queue length is a much better indicator of developer activity, so a custom autoscaler is needed to achieve reasonable behavior. Fair scaling can disrupt ongoing builds because GCP only provides a 90-second shutdown notice before preempting instances, which is not enough time to terminate running actions gracefully. Cold runners are significantly slower than hot ones because they start with empty local caches. To mitigate this, they implemented a solution to reuse runner disks, but only for disks that had been used for builds covering more than 50% of the build graph. This strategy reduced startup times from eight minutes to less than one. The second talk, given by Gabriel Russo from Databricks and Yuval Kaplan from EngFlow, focused on building at scale and how a naive move to remote execution can actually make CI slower. They investigated the specific problem of using Docker in actions. The default behavior for remote actions is to bring up a fresh worker for each execution and tear it down afterward, wiping all state. However, Docker is stateful, which meant that actions were performing a great deal of redundant work. To solve this, they moved the snapshotter (a part of ) out of the action sandbox and into the execution container, allowing it to be shared across all actions on a given machine. The takeaway is that you must be careful with RE. Your intuition for how local processes interact, especially with local state, does not always apply, and you can inadvertently make builds much slower and more expensive. But how do you develop such intuition? That question provides a perfect segue to the next talk. Bazel is a complex piece of software, and its interactions with other systems are not always straightforward. When things go wrong, can the data tell us what happened? Users are often frustrated by unexpected cache misses, frequently rebuilt targets, non-hermetic actions, and flaky tests. This was the topic of a talk co-presented by Eloise Pozzi from Canva and Helen Altshuler from EngFlow. The answer to the question above is obviously yes, the data can tell us. But it’s not easy because there is a lot of data to comb through. Bazel produces the following datasets: Build Event Protocol (BEP): A stream of events that Bazel sends to a remote server to publish build metadata and report progress. The metadata is the closest thing you will get to “usage telemetry” from Bazel as it captures all builds that were executed (who ran them and with which flags, what was executed, etc.) My pet peeve is that the BEP is incredibly complex and really difficult to manipulate post-facto, but I encourage you to generate one locally (via ) and to spend “a few” minutes understanding what’s in there. Exec log: This log captures everything that happened for actions, regardless of where they ran (the BEP only contains minimal details on local-only actions). It is not captured by default due to its verbosity. The flag, available since Bazel 7.1, makes it possible to capture this log unconditionally. Note that you need a parser to convert this binary log into something that can be read and compared across versions, and you need to manually build this parser out of Bazel’s source tree; yikes. Exec graph log: This log captures how actions depend on each other. It can help quantify drag on the critical path, determine if the critical path is unique, or identify if there are competing ones. Use it to identify actions to prioritize for end-to-end build optimization. Query commands: See the reference for , , and . JSON profile: Also known as the performance profile , this captures a timeline of all actions executed by Bazel and can help understand build bottlenecks and tune parallelization. RE profile: Similar to the JSON profile but this is captured server-side by some RE implementations. EngFlow generates one of these with specific details on how the workers executed actions (e.g. which pool ran an action, which is not something that’s visible to Bazel). Returning to the BEP, it’s worth noting that one of the last messages it emits is , which contains links to some of the other logs mentioned above. If you are using remote caching, these links will point to remote cache entries, allowing you to fetch them after the fact for any user build you need to investigate. The talk also included a description of how to debug cache misses between CI and interactive developer builds, and I felt it was an almost-literal rehearsal of the article I wrote months ago on the same topic. The next talk I attended, which hits close to my heart, was on exposing developer tools to the . I believe that provides a terrible user experience, so I was keen to hear about alternatives. The talk was given by Florian Berchtold from Zipline. One possible solution to this dilemma is to use direnv , a long-standing tool that hooks into the shell’s before-prompt command to run arbitrary code when entering specific directories. Scary? Yes. Useful? Also yes. The idea is to leverage direnv to bring project-specific tools into the . But where do these tools come from? While some people use package managers like nixpkgs , this can lead to duplication and inconsistencies in a Bazel-native world. For example, it’s common to pull in via bzlmod, but you might also want to expose it in the . This is where bazel_env comes in: a hook for direnv that fetches tools using Bazel. The talk explained how to use with dev containers to install , , IDE extensions, and even starpls (the LSP for Starlark). It was also mentioned that for C++, bazel-compile-commands-extractor with works reasonably well for VSCode but struggles with large repositories. For those, configure-vscode-for-bazel is recommended for a better experience. The speaker also prepared a sample repository to demonstrate Bazel integration in the IDE for various languages, which you can find at hofbi/bazel-ide . A few months ago, we hosted a Buildbarn mini-conference at Snowflake where, in my opinion, the most exciting talk was Ed Schouten’s presentation on Bonanza. Shortly after, I published an article imagining the next generation of Bazel builds , because Bazel’s fat client model is problematic in many scenarios. At BazelCon, we now heard Google’s approach to solving slow cold builds and Bazel client scalability in a talk on Skycache by Shahan Yang. The core idea of Skycache is to serialize and remotely cache Skyframe , Bazel’s internal tracking system for build state (also known as the “build graph”). In his talk, Shahan outlined three major considerations for making this solution viable: Top-down pruning: When you get a cache hit for a node in the graph, you don’t have to worry about anything below that node anymore. You can throw away everything underneath to keep memory usage constrained. Invalidation computation: To determine what needs to be re-fetched from the cache, Skycache assumes “the same baseline” and then looks for file changes between the local system and the cache to find “what’s missing”. I know, this sounds fuzzy; refer back to the talk for the specifics. Efficiency: For some nodes, it’s cheaper to recompute them than to fetch them from the cache, and this was true for many nodes before applying two optimizations. One was in the nested sets data structure, because the original approach to serializing them caused a 10x space blowup. The other was around serializing individual node values, because most of the time, those values share internals across nodes. Internal dogfooding of Skycache showed that some builds dropped from 46 to 13 seconds, with similar reductions observed for analyzed targets, loaded packages, and more. On the server side, this solution is RAM-intensive (similar to Bazel’s in-memory representations) and is complicated by the fact that users want to build at older versions and with a high version cadence. To be effective, Skycache needs to maintain “thousands of base images”. A specific insight toward the end of the talk was that, for Google as a whole, 2.5% of targets account for 90% of all targets built. This suggests a potential optimization where only those targets are cached, but this has not yet been implemented. There is no open-source implementation of Skycache, but the talk provided hints about which classes would need to be implemented to make it work. It seems that it shouldn’t be too difficult: the serialization code is already in place, so all that’s required is integration with a key-value store and Git. While this talk was fascinating, I can’t help but feel that Google’s solution is a bit strange. They are opting to maintain a fat Bazel client instead of moving it entirely to the cloud, as Bonanza is attempting to do, and this feels weird to me knowing how the rest of their infrastructure works (or used to work a few years back). Yes, this was BazelCon, but given Buck’s spiritual heritage, it was no surprise to see some Buck 2 content. Andreas Herrmann from Tweag took the stage to compare Bazel and Buck 2’s approaches to the efficient compilation of Haskell, highlighting the key role of dynamic actions in Buck 2. The core of the issue lies in how Haskell modules and libraries are compiled and exposed in the Haskell rules. The summary is as follows: Modules are individual source files. These act as the compilation unit. Libraries are collections of modules, and is what’s often modeled in the build via rules. Therefore, library targets tend to group various modules. Compiling an file produces an object file but also a interface file. Think of the latter as a precompiled header or an interface JAR. To compile a module, we need the files of its dependencies, not their files. This is the key difference between compiling a vs. a , because in the C/C++ case, all individual sources can be compiled in any order, but in the Haskell case, they cannot. With this in mind, the central question is: how can we parallelize the compilation of modules within a library when they must be compiled in dependency order? In Bazel, the solution is to model the internal library modules as separate rules, each with a static representation of its cross-module dependencies. However, this approach can be incredibly noisy. While Gazelle can help mitigate the issue, it is still not an ideal user experience. Buck 2, on the other hand, provides dynamic dependencies, which make it possible to infer the module-level dependency graph at build time . The idea is to have an action that runs to emit the cross-module dependency “mini-graph” for a set of modules, and then use a dynamic action to generate module-level compilation actions with the correct dependencies. One of my original critiques of Bazel in 2015 was that while Bazel is excellent at building , it is not well-suited for other workflows. The specific example I gave was that developers want to install the software they have just built (the equivalent of ), which is not easy to model in Bazel. Well, fear no more. Aspect Build is developing a solution to this problem with Starlark-defined tasks and a custom CLI to run them. I found this to be very exciting, and it was a “hot topic” at the hackathon that followed the conference. The premise of the talk was that, even with Bazel, developers still often rely on auxiliary scripts to install tools, Makefiles to drive workflows like setting up test servers or linting code, and YAML files to define complex CI tasks. While all of this should ideally be expressed in Bazel, there is currently no good way to do so. In essence, Bazel is missing a “task runner”, and this is where Aspect’s newly-announced Extension Language (AXL) comes in. It’s a Starlark dialect for running tasks, which requires the Aspect CLI to execute. The CLI is a companion tool to Bazel that once “replaced” Bazel but no longer does. With the new AXL language, you can define tasks in a way that is very similar to defining rules: you create a Starlark function, receive a context, and can then perform “stuff”. The key difference between tasks and rules is that tasks can trivially execute a build with . Even more exciting is the ability to iterate over the BEP events that the build emits and interact with them! The talk also demonstrated the use of WASM binaries for things like buildozer to write platform-agnostic AXL scripts that help with migrations and the like. But the sky is the limit here, and the new aspect-extensions GitHub organization is meant to collect all user-contributed tasks. The desire to create a Bazel foundation to protect the project and ecosystem, should Google ever “pull the plug”, was announced a year ago, but not much has seemed to happen since. In reality, a lot has been going on behind the scenes, but nothing has yet materialized for the average user. As part of the unconference, we voted to have a BoF on the foundation to discuss its future. The main question we tried to answer during the session was, “What could the foundation do ?” Many ideas were brainstormed, including funding a technical writer, improving the quality of pull requests, maintaining important rulesets, and tackling tricky IDE integrations. However, the most popular idea was for the foundation to act as an intermediary between the community and Google, helping to prioritize the projects that the community needs most. I think there is an AI transcript of the session somewhere but there is no recording. You’ll have to stay tuned for the news, or you can get involved via Slack. Reach out to Alex Eagle or Helen Altshuler. When you have a small repository with a single project, you can easily record project settings (such as compilation targets and debug flags) in the top-level file. But what do you do when you start combining multiple projects into one repository? The build settings for a backend service might be different from those required for a frontend application. files are here to help, and Susan Steinman and Greg Estren from Google were on hand to explain them. The key problem being addressed is that while everyone intuitively understands what a “project” is, Bazel lacks a first-class representation of this concept. By introducing such a concept, the goal is to make work consistently everywhere, without the need to specify any flags. This is the opposite of the current situation, where it is common for developers to create auxiliary scripts to run Bazel with different flags for different targets. As for the format of , the presenters reminded us that is an ad-hoc language and one of the few places where Bazel does not use Starlark, despite the community’s desire for consistency. As a result, these new project files are written in the language we have all come to appreciate. More specifically, files can appear multiple times in the directory tree, just like files. The first one found when walking up the tree from a given build target is the one that is used. The file contains a project definition, which in turn contains buildable units. These units can enforce different policies for flags, such as setting default flag values for a target or preventing users from modifying certain flags. Finally, it is also possible to define multiple configurations for a unit (e.g., release vs. development) and to switch between them using . One mistake that everyone makes when moving to a monorepo is retaining operations that scale with the size of the monorepo instead of the size of the change . In particular, it is extremely common to see CI workflows that run , either executing all tests from scratch or hoping that remote caching will prevent the re-running of unmodified tests. This is a bad practice. The overhead is significant, and the end-user experience is often terrible, especially when flaky tests are present. bazel-diff is a tool that helps determine the targets affected by a given code change, allowing Bazel to build and test only those targets. Maxwell Elliott and Connor Wybranowsky were on hand to share the impact that developing this tool at Tinder has had on the company’s developer workflows. The initial results of deploying were a 40% reduction in CI times at the 90th percentile, and up to a 76% reduction in the worst case. These kinds of improvements were transformative for users. In particular, because CI flows became much faster and more accurate, developers began to take ownership of test breakages and flakiness. Unfortunately, as is often the case with “transformative performance improvements” (remember SSDs or the M1 chip?), the codebase continued to grow and eventually consumed all the gains from . To improve on the original deployment, the new approach is to integrate more deeply with CI. The idea is to dynamically generate pipelines based on the changes in a pull request and select which ones to run at review time. For example, if any of the modified files have automated formatters, only the formatter pipelines will be triggered. To recap, the presenters mentioned that the end-to-end adoption of has helped them save up to 93% of their time in CI. While the extra gains beyond the initial 76% did not lead to the same kinds of cultural changes that were originally observed, developers always appreciate faster workflows. If you have attended previous BazelCons, you will know that supply chain security is a recurring topic. This year was no different, with Mark Zeren from Broadcom and Tony Aiuto from Datadog presenting the latest news in this area. The reason this topic is relevant to the conference is that Bazel is a key tool for producing reliable SBOMs, thanks to its hermeticity, sandboxing features, and fine-grained build graph entries. However, it’s not quite there yet. From the beginning, Bazel included as a way to define per-package licensing details. However, this ruleset was “thrown over the wall” by Google when Bazel was first open-sourced and has not been fit for purpose. Today, there is a new ruleset called supply-chain , with only one person from Google on the eight-person team. This new ruleset focuses on two things: metadata rules that code authors can apply to their files, and tools to generate provenance information and produce SBOMs. These two components are separate because the metadata rules are designed to be stable over time, while the tools are expected to change frequently. What is missing from the new ruleset is licensing: the ability to generate copyright notices, validate linkage, and so on. As I mentioned earlier, your intuition about what works well for local actions may not apply to remote actions, and container image building is a prime example of this. In this talk, Malte Poll from Tweag took the stage to introduce rules_img , a new ruleset that replaces and . It is designed to minimize large blob transfers, resulting in significantly more efficient container builds. I do not have written notes on this talk because I was too focused absorbing the many, many details given during the talk, so I strongly encourage you to watch it. To conclude this long recap, I will leave you with my own lightning talk on how our Java integration tests at Snowflake became significantly slower after we migrated from Maven to Bazel. It’s only eight minutes long, but if you want the summary: Maven and Bazel compile Java code differently. Maven writes class files to a few directories on disk, while Bazel creates intermediate JAR files for every Java library. With Bazel’s more-detailed build graph, this causes an explosion in the size and means that class files must be read from compressed JAR (ZIP) files instead of from disk. I spent some time analyzing the problem and ruled out obvious factors like sandboxing and ZIP compression. I concluded that reading from JAR files is indeed slower than reading individual files from disk. (Why? I’m not sure, but I suspect there is an optimization that could be made in the class loader to fix this.) To mitigate the problem, I created a new rule that uses the tool to merge all intermediate JARs into one. But this was easier said than done. The resulting combined JAR was huge and could not be reused across tests, so I had to develop a complex dependency-pruning rule to generate a combined JAR that could be reused across all tests without introducing class duplicates—all while remaining remote-execution-friendly. With this new rule in place, we saw test runtimes drop by about 10 seconds per test, which brought them back to pre-Bazel levels. And with the improvements that Bazel brings to the build, an end-to-end reduction in test times. And that’s a wrap! This has been more of a detailed summary than a brief recap, but my goal was to clean up and share all the notes I took during the conference. Apologies for the many talks I could not cover in this recap. Once again, head to the BazelCon 2025 YouTube playlist for all recordings. If you are involved with Bazel at all or have any interest in build systems, I strongly encourage you to plan to attend next year. You’ll learn a lot from the talks of course, but what’s more, you’ll get to meet key people from tens of companies—people that hold the keys to how modern build tools and scalable development processes are being developed worldwide. The conference, arranged by the Linux Foundation, took place in Atlanta, GA, USA over three days: one for tutorials and two for the main talks. An extra hackathon day, organized by Aspect Build, followed. Unfortunately, a canceled flight meant I missed the tutorials, but I attended the rest of the events. As usual, it was a super-fun time to connect with old acquaintances and an energizing event that left me with plenty of new topics to research. What follows is not a complete summary of the conference, as there were many talks I did not attend and conversations I missed. If you want the full firehose of videos, see the BazelCon 2025 YouTube playlist . And if you want a TL;DR… I’d pick the following highlights: The ecosystem is maturing with becoming mandatory and the BUILD Foundation being a reality in the near horizon. Performance remains a key focus of the Bazel core team and the community, with innovative approaches like Skycache for client-side speed, sophisticated RE improvements for backend efficiency, and new rulesets like that focus on build speed. Community tooling is expanding Bazel’s scope, with projects like Aspect’s task runner aiming to solve long-standing workflow gaps. Training day: There were six different sessions on the Sunday before the conference, and EngFlow is leading training efforts worldwide. Gazelle: C++ support is on the way for this tool. Version 2.0 will simplify the extensions interface and improve performance. BCR Mirror: Cloudflare is now hosting a mirror for the Bazel Central Registry (BCR). You can use it with Bazel 8.4+ by adding to your configuration—and this will become a default in a future release. Documentation: The most common complaint in community surveys remains the documentation and the steep learning curve. To address this, the BCR website now features icons for sponsorship requests, deprecation notices, and provenance attestations. Furthermore, the Starlark documentation has been published and is now easier to read. In a move to empower the community, the documentation has been migrated out of Google’s internal infrastructure and is available at https://preview.bazel.build/ BUILD Foundation: The foundation currently has three founding members (Spotify, Uber, and Canva) and is looking for four more. The initial meeting is scheduled for December 4th. More on this in its own section. Local remote repo caching: This new feature is intended to allow the caching of repository rules across different workspaces. Experimental WASM support: There is experimental support for WASM tools in repo rules to enable platform-independent tooling, but its future is still uncertain. Performance improvements: Changes to can save up to 20% of memory. Optimizations in Merkle tree handling can reduce wall time by up to 30%. Analysis phase caching is coming soon (see the “Skycache” section below for more details). There are ongoing efforts to cap disk usage. Path stripping, a feature announced last year, is now more mature and integrated with more rule sets, offering up to an 84% reduction in build time. Analysis time on flag changes has been reduced. Java improvements: Caching has been improved, and method signature changes no longer affect downstream header builds. Starlark flags: A new scoping API is available for Starlark flags. : A new file is being introduced to provide a canonical place for project owners to map targets to flags. More details on its own section. Starlarkification: This effort is almost complete. All rules are now decoupled, with the exception of a few integration points for C++. As of Bazel 9, autoloading of rules is disabled, which means users must now explicitly all the rules they use. Starlark type system: Type annotations and type-checking are coming to Starlark. The syntax will be supported in Bazel 9, with type-checking planned for Bazel 10. The syntax aims for compatibility with Python 3 types, which introduces some limitations on what can be expressed. JetBrains Bazel plugin: The JetBrains-owned Bazel plugin has reached general availability, making the Google-owned plugin a legacy tool. This new plugin promises a much-improved user experience, as it is faster and better integrates the Bazel build graph with IntelliJ’s native understanding of the project structure, avoiding expensive “sync” steps. Internal APIs: There is ongoing work to separate core logic from service interactions (such as remote builds and file system operations), which sounds very similar to how Buck 2 was designed from the start. Executor types: BuildBuddy provides both managed (OCI, Firecracker, macOS) and self-hosted (Docker, Windows, GPU, and more) executors, each with different performance, isolation, and cost characteristics. Multiple action queues: Executors are organized into pools, and actions can specify which pool they should run on. When an action is received, the scheduler enqueues it in up to three different executors to minimize tail latency, based on the Sparrow scheduler research paper . Work stealing: Dynamic scaling of executor pools is critical for handling spiky build workloads while keeping costs down. To make this more efficient, BuildBuddy allows new executors to steal work from existing ones, which helps redistribute the load. Action merging: This feature coalesces multiple execution requests for the same action into a single execution. As we learned, this can be problematic if a misbehaving executor stalls multiple clients (e.g., several CI jobs). To address this, BuildBuddy speculatively re-executes a running action on a different executor after a certain threshold has passed. Action cancellation: When a user presses Ctrl+C, they are likely to modify code and restart the build, so continuing to run in-flight actions is wasteful. For greater efficiency, BuildBuddy catches the finished event from the BEP and attempts to cancel all remotely-queued actions. Binpacking: Different actions have different resource requirements, and it can be difficult to manually assign them to the right pool and executor. BuildBuddy automatically profiles executed actions (for metrics like peak memory and CPU consumption) and stores this information in the field of the action result, which is then stored on the server. The scheduler uses these details to route actions more effectively. Cold starts: Executing remote actions is similar to running lambda functions: a worker must be started, a container image fetched, and the action executed. To optimize this, BuildBuddy uses affinity routing, where a key is computed based on the primary output name (which is unique for each action) to extract platform, target, and output details. This allows similar actions to be routed to similar executors. Recycled runners: Some customers need to maintain heavyweight processes on the remote worker, such as test databases or the Docker daemon. While not hermetic, this is often desirable for high-performance scenarios. The use of these features is customized through execution properties. Custom resources: Some actions may require access to specialized resources like GPUs, FPGAs, or simulators. For better binpacking, customers can define the “size” of different executor types and annotate actions with the resources they consume. Fair scheduling: With multi-tenancy, users can set a “priority” for the actions of a build using the flag. A common use case is to define three priority bands: interactive builds, CI, and cron jobs. The BuildBuddy scheduler takes this property into account. The default Kubernetes autoscaler relies on CPU and memory utilization for its decisions, but these metrics are poor predictors of CI traffic patterns. Action queue length is a much better indicator of developer activity, so a custom autoscaler is needed to achieve reasonable behavior. Fair scaling can disrupt ongoing builds because GCP only provides a 90-second shutdown notice before preempting instances, which is not enough time to terminate running actions gracefully. Cold runners are significantly slower than hot ones because they start with empty local caches. To mitigate this, they implemented a solution to reuse runner disks, but only for disks that had been used for builds covering more than 50% of the build graph. This strategy reduced startup times from eight minutes to less than one. Build Event Protocol (BEP): A stream of events that Bazel sends to a remote server to publish build metadata and report progress. The metadata is the closest thing you will get to “usage telemetry” from Bazel as it captures all builds that were executed (who ran them and with which flags, what was executed, etc.) My pet peeve is that the BEP is incredibly complex and really difficult to manipulate post-facto, but I encourage you to generate one locally (via ) and to spend “a few” minutes understanding what’s in there. Exec log: This log captures everything that happened for actions, regardless of where they ran (the BEP only contains minimal details on local-only actions). It is not captured by default due to its verbosity. The flag, available since Bazel 7.1, makes it possible to capture this log unconditionally. Note that you need a parser to convert this binary log into something that can be read and compared across versions, and you need to manually build this parser out of Bazel’s source tree; yikes. Exec graph log: This log captures how actions depend on each other. It can help quantify drag on the critical path, determine if the critical path is unique, or identify if there are competing ones. Use it to identify actions to prioritize for end-to-end build optimization. Query commands: See the reference for , , and . JSON profile: Also known as the performance profile , this captures a timeline of all actions executed by Bazel and can help understand build bottlenecks and tune parallelization. RE profile: Similar to the JSON profile but this is captured server-side by some RE implementations. EngFlow generates one of these with specific details on how the workers executed actions (e.g. which pool ran an action, which is not something that’s visible to Bazel). Top-down pruning: When you get a cache hit for a node in the graph, you don’t have to worry about anything below that node anymore. You can throw away everything underneath to keep memory usage constrained. Invalidation computation: To determine what needs to be re-fetched from the cache, Skycache assumes “the same baseline” and then looks for file changes between the local system and the cache to find “what’s missing”. I know, this sounds fuzzy; refer back to the talk for the specifics. Efficiency: For some nodes, it’s cheaper to recompute them than to fetch them from the cache, and this was true for many nodes before applying two optimizations. One was in the nested sets data structure, because the original approach to serializing them caused a 10x space blowup. The other was around serializing individual node values, because most of the time, those values share internals across nodes. Modules are individual source files. These act as the compilation unit. Libraries are collections of modules, and is what’s often modeled in the build via rules. Therefore, library targets tend to group various modules. Compiling an file produces an object file but also a interface file. Think of the latter as a precompiled header or an interface JAR. To compile a module, we need the files of its dependencies, not their files. This is the key difference between compiling a vs. a , because in the C/C++ case, all individual sources can be compiled in any order, but in the Haskell case, they cannot.

0 views
Blog System/5 1 years ago

You are holding BUILD files wrong

I’ve heard it from people new to Bazel but also from people very familiar with the Bazel ecosystem: BUILD files must go away. And they must go away because they are redundant: they just repeat the dependency information that’s already encoded in the in-code import/use statements. Hearing this from newcomers to Bazel isn’t surprising: after all, most newcomers are used to build tools that provide zero facilities to express dependencies across the sources of your own project. Hearing it from old-timers, however, is disappointing because it misses the point of what BUILD files can truly offer. In my opinion: if that’s how you are writing BUILD files, you are holding them wrong. There is much more to BUILD files than mindlessly repeating import statement dependencies. Let’s see why. But before we do, take a moment to subscribe to Blog System/5. You do not want to miss out on future content! Suppose you are given the following change to review: By looking at this diff, possibly from a Pull Request (PR) review, you can guess the following: The Java package already depends on the package. The Java package already depends on the package. The addition of the line does not modify the dependency graph: the edge from the package to the package existed beforehand, and this new import statement is just leveraging it. The addition of the line is… uh, well, given this limited context, you just can’t tell! Is it OK or is it not? Did already depend on via some other file in the same package—in which case this new import changes nothing dependency-wise—or did it not—in which case this new import deserves questioning from a high-level architecture perspective? The snippet I presented above is for Java but, in reality, the problem I described applies to every other language: all languages out there have some sort of import/use statements and all languages have some sort of mechanism to group code in module-like entities. By inspecting standalone changes at the file level, we cannot tell whether new cross-module dependencies are being introduced or not. And being able to reason about modules is critical: we humans work best when we can reason about higher level relationships than files. We think of software as a collection of modules with layered dependencies and constraints that should not be violated. Enforcing these conceptual models via import/use statements is impossible, but the build graph—the very thing that BUILD files define—is the best place to encode them in a programmatic manner. So: my point is that BUILD files give you a chance to encode the high-level architecture of your software project as a graph of dependencies that lives outside of the code. If you keep your BUILD files lean and human-managed, you have a good chance of detecting invalid dependencies from a layering perspective as soon as they are introduced. The word “lean” in the previous paragraph is doing a lot of the heavy lifting though because by “lean” I mean simple BUILD files that define targets that map to concepts. This bypasses “best practices” that dictate one BUILD file per directory because you may need to use recursive globs to group sources into larger conceptual units, and this can also result in reduced build performance because you end up with fewer, larger targets. And that’s fine. For one, if recursive globs are a problem because they end up bundling too many related concepts in one target, you have got a problem with your directory structure and you should fix that. And for another, if larger targets end up hurting build performance, you have got a problem with your modularity and you should work towards breaking those big targets apart. At the end of the day, these two issues are symptoms of having too many unrelated concepts in one module. Simplifying the build structure may result in a transient performance regression, but working towards breaking those apart will help everyone in your organization. None of this is novel though, as these ideas can be found outside of Bazel. Think about shared libraries in large C or C++ projects, multiple Maven modules in a large Java code base, or multiple crates in a large Rust project. If you have ever done any of these, you know that manually defining modules is useful because it forces you and your fellow developers to think in terms of APIs at the module boundaries. Changing the module-level architecture of a project is something that happens infrequently and, when it does, you want the more senior people in the team to question and review such changes. And, for that, you must make these changes visible as soon as they happen. Expressing modules in your build graph is great, but people seem to like having tools to automatically update dependencies based on code changes. This is not incompatible with what I have said so far, but in order to keep a clean software architecture, you will need to have a strong code review culture because any undesirable new edges introduced in a change will have to be vetted up at code review. But… what if they aren’t? Can we do better? Of course we can! Bazel gives us a way to express restrictions via reverse dependencies: aka visibility rules . When you maintain a conceptual dependency graph by hand, you will find cases where you want to express things like: can be consumed from , which is the lowest level layer of the compiler. cannot be consumed from any other layer unless we discuss the implications. Visibility rules allow you to express these restrictions programmatically. The difference with forward dependencies is that, if you ever wanted to use from a module that has not been pre-declared as an allowed consumer, you would need to modify the BUILD file definitions in to widen the visibility rules. This would require talking to the owners of such module, either in person or via the code review, to be allowed as a consumer of those APIs. Now that we know the theory behind my proposal, let’s revisit the package from the earlier example. To enforce our desired architecture, the file in might look like this: This is a “lean” file. It defines a single, conceptual library, and doesn’t bother about specifying source files: it trusts that whatever you throw into the directory truly belongs to that module. Most importantly, the attribute declares that only code within the package is allowed to depend on this library. With this rule in place, the problematic code change we saw earlier (adding an of to the ) would no longer be a silent, ambiguous change. The moment the developer (or the CI system) tries to build the code, they would get an immediate, explicit error from Bazel stating that the target is not allowed to see the target. The architectural violation is caught automatically. The desired conversation with the module owners is now forced to happen, exactly as intended. Finally, we get to the most hyped topic of all times: AI agents. Remember when I said above that a clean conceptual module-based architecture is critical for humans to understand how a project works? Well, guess what, the same applies to AI models. If you try to use AI agents on an existing codebase, you will notice that they try to reason about the current architecture by reading individual file names and their contents, and then chasing through their file-level dependencies. But what if you could make these AI agents to follow your conceptual dependency chain by teaching them, via an MCP server , to follow your build graph? Presumably, their ability to reason would increase because they’d be faced with cleaner concepts that explain the story behind your codebase in big blocks. I hope to have convinced you that manually managing your BUILD files in a Bazel project is a good idea for long-term maintainability and for the successful use of AI tools. For this to be possible, you have to forego the “standard practice” of having very small BUILD targets and instead capture your conceptual modular architecture in the build graph. And once you do that, BUILD files magically become manageable by humans, without the need for fancy automation that pushes complexity under the rug. But that’s just my opinion. I’ve heard it from people new to Bazel but also from people very familiar with the Bazel ecosystem: BUILD files must go away. And they must go away because they are redundant: they just repeat the dependency information that’s already encoded in the in-code import/use statements. Hearing this from newcomers to Bazel isn’t surprising: after all, most newcomers are used to build tools that provide zero facilities to express dependencies across the sources of your own project. Hearing it from old-timers, however, is disappointing because it misses the point of what BUILD files can truly offer. In my opinion: if that’s how you are writing BUILD files, you are holding them wrong. There is much more to BUILD files than mindlessly repeating import statement dependencies. Let’s see why. But before we do, take a moment to subscribe to Blog System/5. You do not want to miss out on future content! The problem Suppose you are given the following change to review: By looking at this diff, possibly from a Pull Request (PR) review, you can guess the following: The Java package already depends on the package. The Java package already depends on the package. The addition of the line does not modify the dependency graph: the edge from the package to the package existed beforehand, and this new import statement is just leveraging it. The addition of the line is… uh, well, given this limited context, you just can’t tell! Is it OK or is it not? Did already depend on via some other file in the same package—in which case this new import changes nothing dependency-wise—or did it not—in which case this new import deserves questioning from a high-level architecture perspective? can be consumed from , which is the lowest level layer of the compiler. cannot be consumed from any other layer unless we discuss the implications.

0 views
Blog System/5 1 years ago

Bazel and glibc versions

Imagine this scenario: your team uses Bazel for fast, distributed C++ builds. A developer builds a change on their workstation, all tests pass, and the change is merged. The CI system picks it up, gets a cache hit from the developer’s build, and produces a release artifact. Everything looks green. But when you deploy to production, the service crashes with a mysterious error: . What went wrong? The answer lies in the subtle but dangerous interaction between Bazel’s caching, remote execution, and differing glibc versions across your fleet. In previous posts in this series, I’ve covered the fundamentals of action non-determinism , remote caching , and execution execution . Now, finally, we’ll build on those to tackle this specific problem. This article dives deep into how glibc versions can break build reproducibility and presents several ways to fix it—from an interesting hack (which spawned this whole series) to the ultimate, most robust solution. Before moving on and getting captivated by the intricate details of the problem, take a moment to support Blog System/5. Suppose you have a pretty standard (corporate?) development environment like the following: Developer workstations (WS). This is where Bazel runs during daily development, and Bazel can execute build actions both locally and remotely. A CI system. This is a distributed cluster of machines that run jobs, including PR merge validation and production release builds. These jobs execute Bazel too, who in turn executes build actions both locally and remotely. The remote execution (RE) system. This is a distributed cluster of worker machines that execute individual Bazel build actions remotely. The key components we want to focus on today are the AC, the CAS, and the workers—all of which I covered in detail in the previous two articles. The production environment (PROD). This is where you deploy binary artifacts to serve your users. No build actions run here. All of the systems above run some version of Linux, and it is tempting to wish to keep such version in sync across them all. The reasons would include keeping operations simpler and ensuring that build actions can run consistently no matter where they are executed. However, this wish is misguided and plain impossible. It is misguided because you may not want to run the same Linux distribution on all three environments: after all, the desktop distribution you run on WS may not be the best choice for RE workers, CI nodes, nor production. And it is plain impossible because, even if you aligned versions to the dot, you would need to take upgrades at some point: distributed upgrades must be rolled out over a period of time (weeks or even months) for reliability, so you’d have to deal with version skew anyway. To make matters more complicated, the remote AC is writable from all of WS, CI, and RE to maximize Bazel cache hits and optimize build times. This goes against best security practices (so there are mitigations in place to protect PROD), but it’s a necessity to support an ongoing onboarding into Bazel and RE. The question becomes: can the Linux version skew among all machines involved cause problems with remote caching? It sure can because C and C++ build actions tend to pick up system-level dependencies in a way that Bazel is unaware of (by default), and those influence the output the actions produce. Here, look at this: The version of glibc leaks into binaries and this is invisible to Bazel’s C/C++ action keys . glibc versions its symbols to provide runtime backwards compatibility when their internal details change, and this means that binaries built against newer glibc versions may not run on systems with older glibc versions. How is this a problem though? Let’s take a look by making the problem specific. Consider the following environment: In this environment, developers run Bazel in WS for their day-to-day work, and CI-1 runs Bazel to support development flows (PR merge-time checks) and to produce binaries for PROD. CI-2 sometimes runs builds too. All of these systems can write to the AC that lives in RE. As it so happens, one of the C++ actions involved in the build of , say , has a tag which forces the action to bypass remote execution. This can lead to the following sequence of events: A developer runs a build on a WS. has changed so it is rebuilt on the WS. The action uses the C++ compiler, so the object files it produces pick up the dependency on glibc 2.28. The result of the action is injected into the remote cache. CI-1 schedules a job to build for release. This job runs Bazel on a machine with glibc 2.17 and leverages the RE cluster which also contain glibc 2.17. Many C++ actions get rebuilt but is reused from the cache. The production artifact now has a dependency on symbols from glibc 2.28. Release engineering picks the output of CI-1, deploys the production binary to PROD, and… boom, PROD explodes: The fact that the developer WS could write to the AC is very problematic on its own, but we could encounter this same scenario if we first ran the production build on CI-2 for testing purposes and then reran it on CI-1 to generate the final artifact. So, what do we do now? In a default Bazel configuration, C and C++ action keys are underspecified and can lead us to non-deterministic behavior when we have a mixture of host systems compiling them. Let’s start with the case where you aren’t yet ready to strictly restrict writes to the AC from RE workers, yet you want to prevent obvious mistakes that lead to production breaks. The idea here is to capture the glibc version that is used in the local and remote environments, pick the higher of the two, and make that version number an input to the C/C++ toolchain. This causes the version to become part of the cache keys and should prevent the majority of the mistakes we may see. WARNING: This is The Hack I recently implemented and that drove me to writing this article series! Prefer the options presented later, but know that you have this one up your sleeve if you must mitigate problems quickly. To implement this hack, the first thing we have to do is capture the local glibc version. We can do this with: One important tidbit here is the use of the file, indirectly via the requirement of stamping. This is necessary to force this action to rerun on every build because we don’t want to hit the case of using an old tree against an upgraded system. As a consequence, we need to modify the script pointed at by script (you have one, right?) to emit the glibc version: The second thing we have to do is capture the remote glibc version. This is… trickier because there is no tag to force Bazel to run an action remotely. Even if we assume remote execution, features like the dynamic spawn strategy or the remote local fallback could cause the action to run locally at random. To prevent problems, we have to detect whether the action is running within RE workers or not, and the way to do that will depend on your environment: The third part of the puzzle is to select the highest glibc version between the two that we collected. We can do this with the following , leveraging ’s flag to compare versions. This flag is a GNU extension… but we are talking about glibc anyway here so I’m not going to be bothered by it : And, finally, we can go to our C++ toolchain definition and modify it to depend on the produced by the previous action: Ta-da! All of our C/C++ actions now encode the highest possible glibc version that the outputs they produce may depend on. And, while not perfect, this is an easy workaround to guard against most mistakes. But can we do better? Of course. Based on the previous articles, what we should think about is plugging the AC hole and forcing build actions to always run on the RE workers. In this way, we would precisely control the environment that generates action outputs and we should be good to go. Unfortunately, we can still encounter problems! Remember how I said that, at some point, you will have to upgrade glibc versions? What happens when you are in the middle of a rolling upgrade to your RE workers? The worker pool will end up with different “partitions”, each with a different glibc version, and you will still run into this issue. To handle this case, you would need to have different worker pools, one with the old glibc version and one with the new version, and then make the worker pool name be part of the action keys. You would then have to migrate from one pool to the other in a controlled manner. This would work well at the expense of reducing cache effectiveness, causing a a big toll on operations, and making the rollout risky because the switch from one pool to another is a all-or-nothing proposition. The real solution comes in the form of sysroots. The idea is to install multiple parallel versions of glibc in all environments and then modify the Bazel C/C++ toolchain to explicitly use a specific one. In this way, the glibc version becomes part of the cache key and all build outputs are pinned to a deterministic glibc version. This allows us to roll out a new version slowly with a code change, pinning the version switch to a specific code commit that can be rolled back if necessary, and keeping the property of reproducible builds for older commits. This is the solution outlined at the end of Picking glibc versions at runtime and is the only solution that can provide you 100% safety against the problem presented in this article. It is difficult to implement, though, because convincing GCC and clang to not use system-provided libraries is tricky and because this solution will sound alien to most of your peers. The problem presented in this article is far from theoretical, but it’s often forgotten about because typical build environments don’t present significant skew across Linux versions. This means that facing new glibc symbols is unlikely, so the chances of ending up with binary-incompatible artifacts are low. But they can still happen, and they can happen at the worst possible moment. Therefore, you need to take action. I’d strongly recommend that you go towards the sysroot solution because it’s the only one that’ll give you a stable path for years to come, but I also understand that it’s hard to implement. Therefore, take the solutions in the order I gave them to you: start with the hack to mitigate obvious problems, follow that up with securing the AC, and finally go down the sysroot rabbit hole. As for the glibc 2.17 mentioned en-passing above, well, it is ancient by today standards at 13 years of age, but it is what triggered this article in the first place. glibc 2.17 was kept alive for many years by the CentOS 7 distribution—an LTS system used as a core building block by companies and that reached EOL a year ago, causing headaches throughout the industry. Personally, I believe that relying on LTS distributions is a mistake that ends up costing more money/time than tracking a rolling release, but I’ll leave that controversial topic for a future opinion post. Imagine this scenario: your team uses Bazel for fast, distributed C++ builds. A developer builds a change on their workstation, all tests pass, and the change is merged. The CI system picks it up, gets a cache hit from the developer’s build, and produces a release artifact. Everything looks green. But when you deploy to production, the service crashes with a mysterious error: . What went wrong? The answer lies in the subtle but dangerous interaction between Bazel’s caching, remote execution, and differing glibc versions across your fleet. In previous posts in this series, I’ve covered the fundamentals of action non-determinism , remote caching , and execution execution . Now, finally, we’ll build on those to tackle this specific problem. This article dives deep into how glibc versions can break build reproducibility and presents several ways to fix it—from an interesting hack (which spawned this whole series) to the ultimate, most robust solution. Before moving on and getting captivated by the intricate details of the problem, take a moment to support Blog System/5. The scenario Suppose you have a pretty standard (corporate?) development environment like the following: Developer workstations (WS). This is where Bazel runs during daily development, and Bazel can execute build actions both locally and remotely. A CI system. This is a distributed cluster of machines that run jobs, including PR merge validation and production release builds. These jobs execute Bazel too, who in turn executes build actions both locally and remotely. The remote execution (RE) system. This is a distributed cluster of worker machines that execute individual Bazel build actions remotely. The key components we want to focus on today are the AC, the CAS, and the workers—all of which I covered in detail in the previous two articles. The production environment (PROD). This is where you deploy binary artifacts to serve your users. No build actions run here. All of the systems above run some version of Linux, and it is tempting to wish to keep such version in sync across them all. The reasons would include keeping operations simpler and ensuring that build actions can run consistently no matter where they are executed. However, this wish is misguided and plain impossible. It is misguided because you may not want to run the same Linux distribution on all three environments: after all, the desktop distribution you run on WS may not be the best choice for RE workers, CI nodes, nor production. And it is plain impossible because, even if you aligned versions to the dot, you would need to take upgrades at some point: distributed upgrades must be rolled out over a period of time (weeks or even months) for reliability, so you’d have to deal with version skew anyway. To make matters more complicated, the remote AC is writable from all of WS, CI, and RE to maximize Bazel cache hits and optimize build times. This goes against best security practices (so there are mitigations in place to protect PROD), but it’s a necessity to support an ongoing onboarding into Bazel and RE. The problem The question becomes: can the Linux version skew among all machines involved cause problems with remote caching? It sure can because C and C++ build actions tend to pick up system-level dependencies in a way that Bazel is unaware of (by default), and those influence the output the actions produce. Here, look at this: The version of glibc leaks into binaries and this is invisible to Bazel’s C/C++ action keys . glibc versions its symbols to provide runtime backwards compatibility when their internal details change, and this means that binaries built against newer glibc versions may not run on systems with older glibc versions. How is this a problem though? Let’s take a look by making the problem specific. Consider the following environment: In this environment, developers run Bazel in WS for their day-to-day work, and CI-1 runs Bazel to support development flows (PR merge-time checks) and to produce binaries for PROD. CI-2 sometimes runs builds too. All of these systems can write to the AC that lives in RE. As it so happens, one of the C++ actions involved in the build of , say , has a tag which forces the action to bypass remote execution. This can lead to the following sequence of events: A developer runs a build on a WS. has changed so it is rebuilt on the WS. The action uses the C++ compiler, so the object files it produces pick up the dependency on glibc 2.28. The result of the action is injected into the remote cache. CI-1 schedules a job to build for release. This job runs Bazel on a machine with glibc 2.17 and leverages the RE cluster which also contain glibc 2.17. Many C++ actions get rebuilt but is reused from the cache. The production artifact now has a dependency on symbols from glibc 2.28. Release engineering picks the output of CI-1, deploys the production binary to PROD, and… boom, PROD explodes:

0 views
Blog System/5 1 years ago

Trusting builds with Bazel remote execution

The previous article on Bazel remote caching concluded that using just a remote cache for Bazel builds was suboptimal due to limitations in what can and cannot be cached for security reasons. The reason behind the restrictions was that it is impossible to safely reuse a cache across users. Or is it? In this article, we’ll see how leveraging remote execution in conjunction with a remote cache opens the door to safely sharing the cache across users. The reason is that remote execution provides a trusted execution environment for actions, and this opens the door to cross-user result sharing. Let’s see why and how. As we saw in the article about action determinism , Bazel’s fundamental unit of execution is the action . Consequently, a remote execution system is going to concern itself with efficiently running individual actions, not builds, and caching the results of those. This distinction is critical because there are systems out there that work differently, such as Microsoft’s CloudBuild , Buildbuddy’s Remote Bazel , or even the shiny and new Bonanza . When we configure remote execution via the flag, Bazel enables the action execution strategy by default for all actions, just as if we had done . But this is only a default and users can mix-and-match remote and local strategies by leveraging the various selection flags or by specifying execution requirements in individual actions. A remote execution system is complicated as it is typically implemented by many services: Multiple frontends. These are responsible for accepting user requests and tracking results. These might include implement a second-level CAS to fan out traffic to clients. A scheduler. This is responsible for enqueuing action requests and distributing them to workers. Whether the scheduler uses a pull or push model to distribute work is implementation dependent. Multiple workers. These are responsible for action execution and are organized in pools of distinct types (workers for x86, workers for arm64, etc.) Internally, a worker is divided into two conceptual parts: the worker itself, which is the privileged service that monitors action execution, and the runner , which is a containerized process that actually runs the untrusted action code. The components of a remote cache (a CAS and an AC). The CAS is essential for communication between Bazel and the workers. The AC, which is optional, is necessary for action caching. The architecture of the cache varies from service to service. For the purposes of this article, I want to focus primarily on the workers and their interactions with the AC and the CAS. I’m not going to talk about frontends nor schedulers except for showing how they help isolate remote action execution from the Bazel process. Let’s look at the interaction between these components in more detail. To set the stage, take a look at the action from this sample build file: The action has two types of inputs: a checked-in source file, , and a file generated during the build, . This distinction is interesting because the way these files end up in the CAS is different: Bazel is the one responsible for uploading into the CAS, but is uploaded by the worker upon action completion. When we ask Bazel to build remotely, and assuming has already been built and cached at some point in the past, we’ll experience something like this: That’s a lot of interactions, right?! Yes; yes they are. A remote execution system is not simple and it’s not always an obvious win: coordinating all of these networked components is costly. The overheads become tangible when dealing with short-lived actions—a better fit for persistent workers—or when you have a sequential chain of actions—a good fit for the dynamic execution strategy . What I want you to notice here, because it’s critical for our analysis, is the shaded area. Note how all interactions within this area are driven by the remote execution service, not Bazel. Once an action enters the remote execution system, neither Bazel nor the machine running Bazel have any way of tampering with the execution of the remote action. They cannot influence the action’s behavior, and they cannot interfere with the way it saves its outputs into the AC and the CAS. And this decoupling, my friend, is the key insight that allows Bazel to safely share the results of actions across users no matter who initiated them. However, the devil lies in the implementation details. Given the above, we now know that remote workers are a trusted environment: the actions that go into a worker are fully specified by their action key and, therefore, whatever they produce and is stored into the AC and the CAS will match that action key. So if we trust the inputs to the action, we can trust its outputs, and we can do this retroactively… right? Well, not so fast. For this to be true, actions must be deterministic, and they aren’t always as we already saw . Some sources of non-determinism are “OK” in this context though, like timestamps, because these come from within the worker and cannot be tampered with. Other sources of non-determinism are problematic though, like this one: An attacker could compromise the network request to modify the content of the downloaded file, but only for long enough to poison the remote cache with a malicious artifact. Once poisoned, they could restore the remote file to its original content and it would be very difficult to notice that the entry in the remote cache did not match the intent of this rule. It is tempting to say: “ah, the above should be fixed by ensuring the checksum of the download is valid”, like this: And I’d say, yes, you absolutely need to do checksum validation because there are legitimate cases where you’ll find yourself writing code like this… in repo rules. Unfortunately, such checks are still insufficient for safe remote execution because, remember: actions can run from unreviewed code, or the code that runs them can be merged into the tree after a careless review (which is more common than you think). Consequently, the only thing you can and must do here is to disable network access in the remote worker. That said, just disabling network access may still be “not good enough” to have confidence in the safety of remote execution. A remote execution system is trying to run untrusted code within a safe production environment: code that could try to attack the worker to escape whatever sandbox/container you have deployed, code that could try to influence other actions running on the same machine, or code that could exfiltrate secrets present in the environment. Securing these is going to come down to standard practices for untrusted code execution, none of which are specific to Bazel, so I’m not going to cover them. Needless to say, it’s a difficult problem. If we have done all of the above, we now have a remote execution system that we can trust to run actions in a secure manner and to store their results in both the AC and the CAS. But… this, on its own, is still insufficient to secure builds end-to-end, and we would like to have trusted end-to-end builds to establish a chain of trust between sources and production artifacts, right? To secure a build, we must protect the AC and restrict writes to it to happen exclusively from the remote workers. Only them, who we have determined cannot be interfered with, know that the results of an action correspond to its declared inputs—and therefore, only them can establish the critical links between an AC entry and one or more files in the CAS. You’d imagine that simply setting would be enough, but it isn’t. A malicious user could still tamper with this flag in transient CI runs or… well, in their local workstation. And it’s because of this latter scenario that the only possible way to close this gap is via network level ACLs: the AC should only be writable from within the remote execution cluster. But… you guessed it: that’s still insufficient. Even if we disallow Bazel clients from writing to the AC, an attacker can still make Bazel run malicious actions outside of the remote execution cluster—that is, on the CI machine locally, which does have network access. Such action wouldn’t record its result in the AC, but the output of the action would go into the CAS, and this problematic action could then be consumed by a subsequent action as an input. The problem here stems from users being able to bypass remote execution by tweaking flags. One option to protect against this situation is the same as we saw before: disallow CI runs of PRs that modify Bazel flags so that users cannot “escape” remote execution. Unfortunately, this doesn’t have great ergonomics because users often need to change the file as part of routine operation. Bazel’s answer to this problem is the widely-unknown invocation policy feature. I say unknown because I do not see it documented in the output of and I cannot find any details about it whatsoever online—yet I know of its existence from my time at Google and I see its implementation in the Bazel code base, so we can reverse-engineer how it works. As the name implies, an invocation policy is a mechanism to enforce specific command-line flag settings during a build or test with the goal of ensuring that conventions and security policies are consistently applied. The policy does so by defining rules to set, override, or restrict the values of flags, such as . The policy is defined using the protobuf message defined in src/main/protobuf/invocation_policy.proto . This message contains a list of messages, each of which defines a rule for a specific flag. The possible rules, which can be applied conditionally on the Bazel command being executed, are: : Sets a flag to a specific value. You can control whether the user can override this value. This is useful for enforcing best practices or build-time configurations. : Forces a flag to its default value, effectively preventing the user from setting it. : Prohibits the use of certain values for a flag. If a user attempts to use a disallowed value, Bazel will produce an error. You can also specify a replacement value to be used instead of the disallowed one. : Restricts a flag to a specific set of allowed values. Any other value will be rejected. To use an invocation policy, you have to define the policy as an instance of the message in text or base64-encoded binary protobuf format and pass the payload to Bazel using the flag in a way that users cannot influence (e.g. directly from your CI infrastructure, not from workflow scripts checked into the repo). Let’s say you want to enforce a policy where the flag is always set to when running the command, and you want to prevent users from overriding this setting. We define the following policy in a file: And then we invoke Bazel like this (again, remember: this flag should be passed by CI in a way that users cannot influence): If you now try to play with the flag, you’ll notice that any overrides you provide don’t work. (Bazel 9 will offer a new flag behavior to error out instead of silently ignoring overrides which will make the experience nicer in this case.) Before concluding, I’d like to show you an interesting outage we faced due to Bazel being allowed to write AC entries from a trusted CI environment. The problem we saw was that, at some point, users started reporting that their builds were completely broken: somehow, the build of our custom singlejar helper tool, a C++ binary that’s commonly used in Java builds, started failing due to the inability of the C++ compiler to find some header files. This didn’t make any sense. If we built the tree at a previous point in time, the problem didn’t surface. And as we discovered later, if we disabled remote caching on a current commit the problem didn’t appear either. Through a series of steps, we found that singlejar’s build from scratch would fail if we tried to build it locally without the sandbox. But… that’s not something we do routinely, so how did this kind of breakage leak into the AC? The problem stemmed from our use of , a flag we had enabled long ago to mitigate flakiness when leveraging remote execution. Because of this flag, we had hit this problematic path: An build started on CI. This build used a remote-only configuration, forcing all actions to run on the remote cluster. Bazel ran actions remotely for a while, but at some point, encountered problems while building singlejar. Because of , Bazel decided to build singlejar on the CI machine, not on the remote worker, and it used the strategy, not the strategy, to do so. This produced an action result that was later incompatible with sandboxed / remote actions. Because of , the “bad” action result was injected into the AC. From here on, any remote build that picked the bad action result would fail. The mitigation to this problem was to flush the problematic artifact from the remote cache, and the immediate solution was to set which… Bazel claims is deprecated and a no-op, but in reality this works and I haven’t been able to find an alternative (at least not in Bazel 7) via any of the other strategy flags. The real solution, however, is to ensure that remote execution doesn’t require the local fallback option for reliability reasons, and to prevent Bazel from injecting AC entries for actions that do not run in the remote workers. With that, this series to revisit Bazel’s action execution fundamentals, remote caching, and remote execution is complete. Which means I can finally tell you the thing that started this whole endeavor: the very specific, cool, and technical solution I implemented to work around a hole in the action keys that can lead to very problematic non-determinism. But, to read on that topic, you’ll have to wait for the next episode! So, make sure to subscribe to Blog System/5 now. The previous article on Bazel remote caching concluded that using just a remote cache for Bazel builds was suboptimal due to limitations in what can and cannot be cached for security reasons. The reason behind the restrictions was that it is impossible to safely reuse a cache across users. Or is it? In this article, we’ll see how leveraging remote execution in conjunction with a remote cache opens the door to safely sharing the cache across users. The reason is that remote execution provides a trusted execution environment for actions, and this opens the door to cross-user result sharing. Let’s see why and how. Remote execution basics As we saw in the article about action determinism , Bazel’s fundamental unit of execution is the action . Consequently, a remote execution system is going to concern itself with efficiently running individual actions, not builds, and caching the results of those. This distinction is critical because there are systems out there that work differently, such as Microsoft’s CloudBuild , Buildbuddy’s Remote Bazel , or even the shiny and new Bonanza . When we configure remote execution via the flag, Bazel enables the action execution strategy by default for all actions, just as if we had done . But this is only a default and users can mix-and-match remote and local strategies by leveraging the various selection flags or by specifying execution requirements in individual actions. A remote execution system is complicated as it is typically implemented by many services: Multiple frontends. These are responsible for accepting user requests and tracking results. These might include implement a second-level CAS to fan out traffic to clients. A scheduler. This is responsible for enqueuing action requests and distributing them to workers. Whether the scheduler uses a pull or push model to distribute work is implementation dependent. Multiple workers. These are responsible for action execution and are organized in pools of distinct types (workers for x86, workers for arm64, etc.) Internally, a worker is divided into two conceptual parts: the worker itself, which is the privileged service that monitors action execution, and the runner , which is a containerized process that actually runs the untrusted action code. The components of a remote cache (a CAS and an AC). The CAS is essential for communication between Bazel and the workers. The AC, which is optional, is necessary for action caching. The architecture of the cache varies from service to service. That’s a lot of interactions, right?! Yes; yes they are. A remote execution system is not simple and it’s not always an obvious win: coordinating all of these networked components is costly. The overheads become tangible when dealing with short-lived actions—a better fit for persistent workers—or when you have a sequential chain of actions—a good fit for the dynamic execution strategy . What I want you to notice here, because it’s critical for our analysis, is the shaded area. Note how all interactions within this area are driven by the remote execution service, not Bazel. Once an action enters the remote execution system, neither Bazel nor the machine running Bazel have any way of tampering with the execution of the remote action. They cannot influence the action’s behavior, and they cannot interfere with the way it saves its outputs into the AC and the CAS. And this decoupling, my friend, is the key insight that allows Bazel to safely share the results of actions across users no matter who initiated them. However, the devil lies in the implementation details. Securing the worker Given the above, we now know that remote workers are a trusted environment: the actions that go into a worker are fully specified by their action key and, therefore, whatever they produce and is stored into the AC and the CAS will match that action key. So if we trust the inputs to the action, we can trust its outputs, and we can do this retroactively… right? Well, not so fast. For this to be true, actions must be deterministic, and they aren’t always as we already saw . Some sources of non-determinism are “OK” in this context though, like timestamps, because these come from within the worker and cannot be tampered with. Other sources of non-determinism are problematic though, like this one: An attacker could compromise the network request to modify the content of the downloaded file, but only for long enough to poison the remote cache with a malicious artifact. Once poisoned, they could restore the remote file to its original content and it would be very difficult to notice that the entry in the remote cache did not match the intent of this rule. It is tempting to say: “ah, the above should be fixed by ensuring the checksum of the download is valid”, like this: And I’d say, yes, you absolutely need to do checksum validation because there are legitimate cases where you’ll find yourself writing code like this… in repo rules. Unfortunately, such checks are still insufficient for safe remote execution because, remember: actions can run from unreviewed code, or the code that runs them can be merged into the tree after a careless review (which is more common than you think). Consequently, the only thing you can and must do here is to disable network access in the remote worker. That said, just disabling network access may still be “not good enough” to have confidence in the safety of remote execution. A remote execution system is trying to run untrusted code within a safe production environment: code that could try to attack the worker to escape whatever sandbox/container you have deployed, code that could try to influence other actions running on the same machine, or code that could exfiltrate secrets present in the environment. Securing these is going to come down to standard practices for untrusted code execution, none of which are specific to Bazel, so I’m not going to cover them. Needless to say, it’s a difficult problem. Securing the build If we have done all of the above, we now have a remote execution system that we can trust to run actions in a secure manner and to store their results in both the AC and the CAS. But… this, on its own, is still insufficient to secure builds end-to-end, and we would like to have trusted end-to-end builds to establish a chain of trust between sources and production artifacts, right? To secure a build, we must protect the AC and restrict writes to it to happen exclusively from the remote workers. Only them, who we have determined cannot be interfered with, know that the results of an action correspond to its declared inputs—and therefore, only them can establish the critical links between an AC entry and one or more files in the CAS. You’d imagine that simply setting would be enough, but it isn’t. A malicious user could still tamper with this flag in transient CI runs or… well, in their local workstation. And it’s because of this latter scenario that the only possible way to close this gap is via network level ACLs: the AC should only be writable from within the remote execution cluster. But… you guessed it: that’s still insufficient. Even if we disallow Bazel clients from writing to the AC, an attacker can still make Bazel run malicious actions outside of the remote execution cluster—that is, on the CI machine locally, which does have network access. Such action wouldn’t record its result in the AC, but the output of the action would go into the CAS, and this problematic action could then be consumed by a subsequent action as an input. The problem here stems from users being able to bypass remote execution by tweaking flags. One option to protect against this situation is the same as we saw before: disallow CI runs of PRs that modify Bazel flags so that users cannot “escape” remote execution. Unfortunately, this doesn’t have great ergonomics because users often need to change the file as part of routine operation. Bazel’s answer to this problem is the widely-unknown invocation policy feature. I say unknown because I do not see it documented in the output of and I cannot find any details about it whatsoever online—yet I know of its existence from my time at Google and I see its implementation in the Bazel code base, so we can reverse-engineer how it works. Invocation policies As the name implies, an invocation policy is a mechanism to enforce specific command-line flag settings during a build or test with the goal of ensuring that conventions and security policies are consistently applied. The policy does so by defining rules to set, override, or restrict the values of flags, such as . The policy is defined using the protobuf message defined in src/main/protobuf/invocation_policy.proto . This message contains a list of messages, each of which defines a rule for a specific flag. The possible rules, which can be applied conditionally on the Bazel command being executed, are: : Sets a flag to a specific value. You can control whether the user can override this value. This is useful for enforcing best practices or build-time configurations. : Forces a flag to its default value, effectively preventing the user from setting it. : Prohibits the use of certain values for a flag. If a user attempts to use a disallowed value, Bazel will produce an error. You can also specify a replacement value to be used instead of the disallowed one. : Restricts a flag to a specific set of allowed values. Any other value will be rejected. An build started on CI. This build used a remote-only configuration, forcing all actions to run on the remote cluster. Bazel ran actions remotely for a while, but at some point, encountered problems while building singlejar. Because of , Bazel decided to build singlejar on the CI machine, not on the remote worker, and it used the strategy, not the strategy, to do so. This produced an action result that was later incompatible with sandboxed / remote actions. Because of , the “bad” action result was injected into the AC. From here on, any remote build that picked the bad action result would fail.

0 views
Blog System/5 1 years ago

Understanding Bazel remote caching

The previous article on Bazel action non-determinism provided an introduction to actions: what they are, how they are defined, and how they act as the fundamental unit of execution in Bazel. What the article did not mention is that actions are also the fundamental unit of caching during execution to avoid doing already-done work. In this second part of the series, I want to revisit the very basics of how Bazel runs actions and how remote caching ( not remote execution, because that’ll come later) works. The goal here is to introduce the Action Cache (AC) , the Content Addressable Storage (CAS) , how they play together, and then have some fun in describing the many ways in which it’s possible to poison such a cache in an accidental or malicious manner. Picture this build file with two targets that generate one action each: And now this sequence of commands: : This first command causes Bazel to build , possibly from scratch. This takes at least 10 seconds due to the calls we introduced in the commands. As a side-effect of this operation, Bazel populates its in-memory graph with the actions that it executed and the outputs they produced. : This second command asks Bazel to do the same build as the first command and, because we just built and Bazel’s in-memory state is untouched, we expect Bazel to do absolutely nothing. In fact, this command completes (or should complete) in just a few milliseconds due to Bazel’s design. : This third command shuts the background local Bazel server process down. All in-memory state populated by the first command is lost. : This fourth command asks Bazel to do the same build as the first and second commands. We didn’t run a so all on-disk state is still present, so we should expect Bazel to not rebuild nor . And indeed they are not rebuilt: Bazel also “does nothing” like in that second command (the s don’t run), but the build is visibly slower in this case. The problem or, rather, question is… how does Bazel know that there is nothing to do on that fourth command? A system like Make would discover that all output files are “up to date” by comparing their timestamps against those of their inputs, but remember that Bazel tracks output staleness by inspecting the content digests of the inputs and ensuring they haven’t changed. Enter the Action Cache (AC) : an on-disk persistent cache that helps Bazel determine whether the outputs of an action are already present on disk and whether they already have the expected (up-to-date) content. The AC lives under and is stored in a special binary format that you can dump with . Conceptually, the AC maps the s that we saw in the previous article to their corresponding s. In practice, the AC keys are a more succinct representation of the on-disk state of the inputs to the action: up until Bazel 9, the keys were known as “digest keys” but things have changed recently to allow Bazel to better explain why certain actions are rebuilt; the details are uninteresting in this article though. But what is an ? The “action result” records, well, the side-effects of the action. Among other things, the contains: The exit code of the process executed by the action. A mapping of output names to output digests . The mapping of output names to digests is the piece of information I want to focus on because this is what allows the fourth Bazel invocation above to discover that it has “nothing to do”. When Bazel has lost its in-memory state of an action, Bazel queries the AC to determine the names of its outputs. If those files exist on disk, then Bazel can compute their digests and compare those against the digests recorded in the . If they match, Bazel can conclude that the action does not have to be re-executed. And this explains why the fourth Bazel invocation is visibly slower than the second invocation, even if both are “fully cached”: when the in-memory state of an action is lost, Bazel has to re-digest all input and output files that are on disk, and these are slow operations, typically I/O-bound. If you have seen annoying pauses with the message, you now know what they are about. The AC is, maybe surprisingly, a concept that exists even if Bazel is not talking to a remote cache or execution system. But what happens when we introduce a remote cache into the mix? First of all, the remote cache needs to be able to answer the same questions as the local AC: “given an action key, is the action result already known?” But let’s think through what goes into the result of such a query. Does the remote AC capture the same information that goes into a local , or does it do something different? Given that we are talking about a remote cache, it’s tempting to say that the value of the cache entry should embed the content of the output files: after all, if Bazel scores a remote AC hit, Bazel will need to retrieve the resulting output files to use them for subsequent actions, right? Not so fast: What if Bazel already has the output files on disk but is just querying the remote AC because the local in-memory state was lost? In this case, you want the response from the cache to be as small and quick as possible: you do not want to fetch the output contents again because they may be very large. What if you (the user) don’t care about the output’s content? Take a look at the actions in the example above: if all of them are cached, when I ask Bazel to build I probably only want to download from the remote cache. I may not care about the intermediate , so why should I be forced to fetch it when I query the cache just to know if is known? What if I'm using remote execution and I'm building and running a test? The test runs remotely, so the local machine does not need to download any file at all! This is why the , even for the remote AC, does not contain the content of the outputs. But then… how is the remote cache ever useful across users or machines, or even in a simple sequence like this? The in between these two builds causes all disk state (the local AC and the local output tree) to be lost. In this situation, Bazel will leverage the remote AC to know the names of the output files and their digests for each action… but if those outputs are not present on the local disk anymore, then what? Do we just rebuild the action? That’d… work, but it’d defeat the whole purpose of remote caching. Enter the Content Addressable Storage (CAS) , another cache provided by the remote caching system to solve this problem. The CAS maps file digests ( not names!) to their contents . Nothing more, nothing less. By leveraging both the AC and the CAS, Bazel can recreate its on-disk view of an already-built target by first checking with the AC what files should exist and then leveraging the CAS to fetch those files. Let’s visualize everything explained above via sequence diagrams. This first diagram represents the initial invocation, assuming that has not been built at all by anyone beforehand. This means that Bazel will not be able to score any local nor remote AC hits and therefore will have to execute all actions: This second diagram represents the second invocation executed after . In this case, all local state has been lost, but Bazel is able to score remote cache hits and recreate the local disk state by downloading entries from the remote AC and CAS. The dashed lines against the CAS represent optional operations, controlled by the use (or not) of the “Build Without The Bytes” feature. Before moving on to the fun stuff, a little subtlety: whenever the AC and CAS use digests, they don’t just use a hash. Instead, they use hash/size pairs. This adds extra protection against length extension attacks and allows both Bazel and the remote cache to cheaply detect data inconsistencies should they ever happen. With any remote caching system, we must fear the possibility of invalid cached entries. We have two main types of “invalid entries” to worry about: Actions that point to results that, when reused, lead to inconsistent or broken builds. This can happen if the cache keys fail to capture some detail of the execution environment. For example: if we have different glibc versions on the machines that store action results into the remote cache, we can end up with object files that are incompatible across machines because the glibc version is not part of the cache key. Actions that point to malicious results injected by a malicious actor. The attack vector looks like this: a malicious actor makes a action point to a poisoned object file that steals credentials and uploads them to a remote server. This object file is later pulled by other machines when building tools that engineers run or when building binaries that end up in production, leading to the compromised code spreading to those binaries. Scary stuff. But can this attack vector happen? Let’s see how an attacker might try to compromise the remote cache. If the attacker can inject a malicious blob into the CAS, we now have a new entry indexed by its digest that points to some dangerous file. But… how can we access such file? To access such file, we must first know its digest. Bazel uses the digests stored in the AC to determine which files to download from the CAS so, as long as there is no entry in the AC pointing to the bad blob, the bad blob is invisible to users and is not used. We have no problem here. The real danger comes from an attacker having write access to the AC. If the attacker can write arbitrary entries to the AC, they can pretty much point any action to compromised results. Therefore, the content of the AC is precious. In order to offer a secure and reliable remote cache system, we must restrict who can write to the cache. And because we can’t control what users do on their machines (intentionally or not), the only option we have is to restrict writes to the AC to builds that run on CI. After all, CI is a trusted environment so we can assume attackers cannot compromise it. But that’s not enough! Attackers can still leverage a naive CI system to inject malicious outputs into the cache. Consider this: an attacker creates a PR that modifies the scripts executed by CI. This change leverages the credentials of the CI system to write a poisoned entry into the AC. This poisoned entry targets an action that almost-never changes (something at the bottom of the build graph) to prevent it from being evicted soon after. The attacker runs the PR through CI and then deletes the PR to erase traces of their actions. From there on, the poisoned artifact remains in the cache and can be reused by other users. Yikes. How do we protect against this? The reality is that we just cannot, at least not in a very satisfactory way. If the CI system runs untrusted code as submitted in a PR, the CI system can be compromised. We can mitigate the threat by doing these: For CI runs against PRs (code not yet reviewed and merged): Disallow running the CI workflows if the changes modify the CI infrastructure in any way (CI configurations, scripts run by CI, the Bazel configuration files, etc.) Configure Bazel with so that s or other actions that could produce tampered outputs cannot propagate those to other users. For CI runs against merged code: Configure Bazel with so that they are the only ones that can populate the remote cache. If there is any malicious activity happening at this stage, which could still happen via sloppy code reviews or smart deceit, at least you will be able to collect audit logs and have the possibility of tracing back the bad changes to a person. This configuration should provide a reasonably secure system at the expense of slightly lower cache hit rates: users will not be able to benefit from cached artifacts until their code has been merged and later built by CI. But… doing otherwise would be reckless. Before concluding: what about the CAS? Is it truly safe to allow users to freely write to the CAS? As we have seen before, it is really difficult for a malicious entry in the CAS to become problematic unless it is referenced by the AC. But still, we have a couple of scenarios to worry about: DoS attacks: Malicious users could bring the remote cache “down” (making it less effective) by flooding the CAS with noise, pushing valid artifacts out of it, or by exhausting all available network bandwidth. This is not a big concern in a corporate environment where you'd be able to trace abusive load to a user, but you might still run into this due to accidental situations. Information disclosure: If a malicious user can somehow guess the digest of a sensitive file (e.g. a file with secrets), they could fetch such file. So… how much do you trust cryptography? As presented in this article, deploying an effective remote cache for Bazel in a manner that’s secure is not trivial. And if you try to make the setup secure, the effectiveness of the remote cache is lower than desirable because users can only leverage remote caching for builds executed on CI: any builds they run locally, possibly with configurations that CI doesn’t plan for, won’t be cached. The only way to offer a truly secure remote caching system is by also leveraging remote execution. But we’ll see how and why in the next episode. Make sure to subscribe to Blog System/5 to not miss out on the promised follow-up! The previous article on Bazel action non-determinism provided an introduction to actions: what they are, how they are defined, and how they act as the fundamental unit of execution in Bazel. What the article did not mention is that actions are also the fundamental unit of caching during execution to avoid doing already-done work. In this second part of the series, I want to revisit the very basics of how Bazel runs actions and how remote caching ( not remote execution, because that’ll come later) works. The goal here is to introduce the Action Cache (AC) , the Content Addressable Storage (CAS) , how they play together, and then have some fun in describing the many ways in which it’s possible to poison such a cache in an accidental or malicious manner. The Action Cache (AC) Picture this build file with two targets that generate one action each: And now this sequence of commands: : This first command causes Bazel to build , possibly from scratch. This takes at least 10 seconds due to the calls we introduced in the commands. As a side-effect of this operation, Bazel populates its in-memory graph with the actions that it executed and the outputs they produced. : This second command asks Bazel to do the same build as the first command and, because we just built and Bazel’s in-memory state is untouched, we expect Bazel to do absolutely nothing. In fact, this command completes (or should complete) in just a few milliseconds due to Bazel’s design. : This third command shuts the background local Bazel server process down. All in-memory state populated by the first command is lost. : This fourth command asks Bazel to do the same build as the first and second commands. We didn’t run a so all on-disk state is still present, so we should expect Bazel to not rebuild nor . And indeed they are not rebuilt: Bazel also “does nothing” like in that second command (the s don’t run), but the build is visibly slower in this case. The exit code of the process executed by the action. A mapping of output names to output digests . What if Bazel already has the output files on disk but is just querying the remote AC because the local in-memory state was lost? In this case, you want the response from the cache to be as small and quick as possible: you do not want to fetch the output contents again because they may be very large. What if you (the user) don’t care about the output’s content? Take a look at the actions in the example above: if all of them are cached, when I ask Bazel to build I probably only want to download from the remote cache. I may not care about the intermediate , so why should I be forced to fetch it when I query the cache just to know if is known? What if I'm using remote execution and I'm building and running a test? The test runs remotely, so the local machine does not need to download any file at all! This second diagram represents the second invocation executed after . In this case, all local state has been lost, but Bazel is able to score remote cache hits and recreate the local disk state by downloading entries from the remote AC and CAS. The dashed lines against the CAS represent optional operations, controlled by the use (or not) of the “Build Without The Bytes” feature. Before moving on to the fun stuff, a little subtlety: whenever the AC and CAS use digests, they don’t just use a hash. Instead, they use hash/size pairs. This adds extra protection against length extension attacks and allows both Bazel and the remote cache to cheaply detect data inconsistencies should they ever happen. Let’s poison the cache With any remote caching system, we must fear the possibility of invalid cached entries. We have two main types of “invalid entries” to worry about: Actions that point to results that, when reused, lead to inconsistent or broken builds. This can happen if the cache keys fail to capture some detail of the execution environment. For example: if we have different glibc versions on the machines that store action results into the remote cache, we can end up with object files that are incompatible across machines because the glibc version is not part of the cache key. Actions that point to malicious results injected by a malicious actor. The attack vector looks like this: a malicious actor makes a action point to a poisoned object file that steals credentials and uploads them to a remote server. This object file is later pulled by other machines when building tools that engineers run or when building binaries that end up in production, leading to the compromised code spreading to those binaries. For CI runs against PRs (code not yet reviewed and merged): Disallow running the CI workflows if the changes modify the CI infrastructure in any way (CI configurations, scripts run by CI, the Bazel configuration files, etc.) Configure Bazel with so that s or other actions that could produce tampered outputs cannot propagate those to other users. For CI runs against merged code: Configure Bazel with so that they are the only ones that can populate the remote cache. If there is any malicious activity happening at this stage, which could still happen via sloppy code reviews or smart deceit, at least you will be able to collect audit logs and have the possibility of tracing back the bad changes to a person. DoS attacks: Malicious users could bring the remote cache “down” (making it less effective) by flooding the CAS with noise, pushing valid artifacts out of it, or by exhausting all available network bandwidth. This is not a big concern in a corporate environment where you'd be able to trace abusive load to a user, but you might still run into this due to accidental situations. Information disclosure: If a malicious user can somehow guess the digest of a sensitive file (e.g. a file with secrets), they could fetch such file. So… how much do you trust cryptography?

0 views
Blog System/5 1 years ago

Bazel and action (non-) determinism

A key feature of Bazel is its ability to produce fast, reliable builds by caching the output of actions. This system, however, relies on a fundamental principle: build actions must be deterministic. For the most part, Bazel helps ensure that they are, but in the odd cases when they aren’t, builds can fail in subtle and frustrating ways, eroding trust in the build system. This article is the first in a series on Bazel’s execution model. Having explained these concepts many times, I want to provide a detailed reference before explaining a cool solution to a problem I recently developed at work. We will start with action non-determinism, then cover remote caching and execution, and finally, explore the security implications of these features. This first article explains what non-determinism is, how it manifests, and how you can diagnose and prevent it in your own builds. Let’s begin. Consider the following example build file: This build file specifies two targets : the target, which builds a C library from two source files, and the target, which builds a C binary from one source file and links it against the library. These two targets instantiate the and rules by binding them to specific attributes (the values of and ). Processing these rules during dependency analysis yields a collection of actions : The rule used to define the target generates: A action to compile the file into the object file. Its command line may be: “ A action to compile the file into the object file. Its command line may be: “ A action to link and together into the archive. Its command line may be: “ The rule used to define the target generates: A action to compile the file into the object file. Its command line may be: “ A action to link and together into the executable. Its command line may be: “ Note that nowhere in the list above do you see target names. Actions work with file -level dependencies, not target -level dependencies. If you need to visualize this, think of the target dependency graph and the action dependency graph as two disjoint entities. (Skyframe tracks them as just one graph but we can ignore that fact here.) It’s this, actions, that are the atomic unit of execution in Bazel. Once Bazel is done with its loading and analysis phases, it enters the execution phase. During execution, the “only” thing that Bazel does is dispatch actions for execution via its execution strategies , trying to maximize parallelism as determined by the constraints of the action dependency graph. To break down an action into its parts, let’s examine what goes into defining the action above, and to do that, let’s first focus on its simple command line to produce the binary from the object file and the static library: Bazel tracks the command line as part of the action, but things are a bit more complex than that. And to explain the “complexity”, let’s try to understand what problems Bazel is trying to solve compared to a more rudimentary build tool like Make. If you have used (or still use) Make, you would have likely expressed the corresponding build rule as: which looks… OK, I guess. But what happens if you do this? An inconsistent build! The binary is not stripped as you would expect because the second invocation does nothing ! has no idea that the variable is involved in the target definition so it doesn’t know that the target has to be rebuilt to honor the variable change. This type of scenario is what leads to having to run from time to time in a Make-based build system because the outputs that Make produces get out of sync with environmental changes. And the reason is that the only thing that tracks to determine whether a target needs to be rebuilt are the file timestamps of the inputs that are explicitly listed in the rule ( and in this example). Now you’d say: but you can fix it! “Just” do: And indeed this ensures that the target gets re-linked if changes. But I hope you’ll agree that this is awful and that nobody does it because: one, most folks writing s aren’t aware of the problem; and, two, even if they are, it’s too hard to get it right (see… we forgot about the value of and whatever other environment variables might influence ’s behavior like, you know, the ?). I didn’t come here to bash against Make. OK, maybe I did because folks out there often say “Make works just fine and it’s much simpler than Bazel!” when in reality they are oblivious to a bunch of very real problems that later waste other people ’s time when their build environment subtly breaks. </rant> Bazel and other next-generation build systems solve this specific problem and more by being comprehensive about what they track at the action level, and using that information to determine whether an action needs to be rebuilt or not. In particular, a Bazel action is defined by these parts: The command line to execute , which in this case is . Hashes of the input files required to execute the command. These include “obvious” inputs like the source files specified in the targets but also the files required to execute the tools of the action (e.g. the compiler’s own files). In this case, the list of input files could look like: , , and . The configuration of the environment in which the action runs. This includes environment variables, the host and target platforms, and things like that. In this case, the configuration could include the value of and whether we are building in debug or optimized mode. Configurations are expressed as a hash, though, because of the many details that go into computing them. These three properties define quite precisely the relation between the context of an action and the outputs it produces, and this is the main technique that Bazel uses to avoid clean builds at large scale. Enjoying the article so far? Please subscribe to show your support. But pay attention to the “quite” word in “quite precisely” right above. I did not say “perfectly” because there are still ways for non-deterministic behavior to leak into a Bazel build, meaning that and unexpected rebuilds (e.g. due to cache expiration) could still change the behavior of a build. Consider this innocuous example: This rule says: stick the output of the command, which prints the current date, into the file. Obviously, “current date” varies over time so we should expect the above to give us trouble. And indeed it does: look at this sequence of commands where I’ve removed all irrelevant Bazel console noise: The first Bazel build claims to have executed 1 action in the sandbox and the file shows us the date when that happened. The second Bazel build does nothing and remains unmodified. But if we later follow that by a Bazel clean and a third Bazel build, we see that the content of is now different. Non-determinism has leaked into the build, and… that’s problematic. Non-determinism is a problem because it prevents achieving reproducible builds . On the one hand, this voids the security guarantees that come from being able to reproduce builds in different environments: if the output of the build is not bit-for-bit identical to its inputs, you can’t verify that a binary that’s being used in production actually comes from the sources it claims to have been built from. On the other hand, this leads to situations where developers get different behavior depending on when/where they build the code: you do not want to hear the “works on my machine” excuse when troubleshooting a bug. So, it is bad. But one interesting property of Bazel’s action model is that a single non-deterministic action does not necessarily poison the whole build. Take a look at this build file that defines a chain of actions: The interesting bit here is in the target, which counts the lines in its input and writes the resulting number to its output. While this target consumes a non-deterministic input, its output is deterministic because the number of lines in the input is constant: writes a different timestamp each time, but it always produces one line. The fact that the target produces a deterministic output allows Bazel to stop “propagating” non-determinism across the build. Remember that actions track input hashes , not input timestamps . Once is re-executed after changes to , the output of will have the same hash as it did before, and will conclude that it doesn’t need to be rerun. Let’s try it: The sequence of commands above proves the point: the first build of the target tells us that Bazel executed 4 sandboxed actions (one for each target). If we then remove the non-deterministic file from the output tree and ask Bazel to rebuild the target, we see how it only rebuilt 3 targets and 1 of them scored a cache hit. And by inspecting the log we asked Bazel to produce, we see that it effectively rebuilt , , and , but it didn’t have to rebuild because the non-determinism didn’t propagate further. In a Make world, the above sequence of commands would have invalidated the whole build because Make just checks timestamps, and targets almost-always update the timestamps of their outputs unless we go through great extents to prevent it (like I did earlier on in the stamp file rule with its call to ). In the previous example, it was rather obvious that a call to could be problematic. But this is not the only source of non-determinism, and oftentimes the reason behind the non-determinism isn’t as obvious. Here is a more comprehensive list of possible causes: Date and time. You might not be calling , but build tools—especially code generators and archivers like zip—love injecting timestamps in their output files. These may be obvious, like comments in generated files, or subtle, like values written in binary metadata headers. System identifiers. Similarly to “current date”, there are tools that query the current PID, UID, GID, etc. and inject those values in their outputs. Sort ordering. Hash tables are the star data structure in computer science and they are everywhere. Unfortunately, there are tools that leak their internal use of hash tables into output files by, for example, emitting unsorted lists. Accessing the network. Just don’t . Unexpected/unknown dependencies on host tools. Calling a tool from the system means introducing hidden dependencies on whatever the tool itself depends on. For example, the tool might read a configuration file that alters its behavior. Dynamic execution . This powerful feature that helps improve incremental build times in interactive scenarios can easily lead to non-determinism if the remote execution environment and the local execution environment aren’t equivalent (where equivalent is tricky to define). Foreign CC rules . Bazel tries to enforce action determinism as we saw earlier, but other build systems make little efforts to do so. If you end up nesting build systems, as is the case when using this ruleset, it’s very likely that you are introducing non-determinism. Randomness. Tools can decide to read from and do something with that value, in which case you definitely have non-determinism. The list above is long, and there is this assumption, especially from newcomers to Bazel, that Bazel’s sandboxing ensures that build behavior is deterministic. In a theoretical world, that would be true: Bazel would execute each action in a precisely controlled environment to ensure that actions behaved exactly the same from run to run. This would require using a cycle-accurate virtual machine to precisely control instruction scheduling (multithreading can also introduce non-determinism) and entropy sources, but as you can imagine, this would make build execution extremely slow. In a practical world, sandboxing has to grant some concessions in the name of performance: otherwise, people will end up disabling sandboxing , nullifying all of its benefits. Furthermore, sandboxing isn’t something magical you can “do” from userspace (unless you write a full machine emulator). Sandboxing requires kernel support, and different kernels offer different sandboxing technologies. In turn, this means that what Bazel can sandbox or not depends on the machine that Bazel is running on. For example: Bazel’s sandbox on Linux is able to restrict file accesses, offer stable PIDs, and forbid network accesses—but the macOS sandbox, based on the deprecated sandbox-exec , cannot mangle the PID namespace. So. We know non-deterministic actions can exist in a Bazel build and that sandboxing isn’t going to protect us from them. In that case, how can we tell if such actions have leaked into our build? We can use the “execution log” feature in Bazel to write a detailed log of all the actions that Bazel executes. Then, we can the logs of two separate builds and see if they differ. Looking back to our chain of actions from the last example, we could capture two fresh execution logs by doing this: Note: it is important to start from a clean build and to tell Bazel to not reuse remotely-cached actions. In this way, we force Bazel to reexecute the whole build, which should uncover non-determinism if it exists. Also, make sure to keep enabled (the default). Once we have run the above, we can proceed to diff the logs. I like doing , but you can use whichever file diffing UI you prefer: Voila. The first chunk of the log tells us that the first non-deterministic action is the one that writes the file, and the second chunk of the log tells us that there is another action that consumes said file as an input. Let’s finish the article by giving you some practical tips to remove non-determinism from the build and to make sure it doesn’t come back: Set up a CI pipeline that identifies new instances of non-determinism . Unless you are proactive about it, non-determinism will creep back in because neither the local sandbox not remote execution can fully prevent it. Keep the local sandbox enabled. It may not be perfect but it’s much better than nothing. Also, enable explicitly because, for historical reasons, the sandbox did not forbid network access and the default hasn’t been flipped yet. Rely on hermetic toolchains. Do not use the system-provided ones because they tend to have dependencies on system-provided files that are invisible to the Bazel action definitions. (E.g. if you use the host-provided , the compiler will happily embed into the final binary and this will be invisible to Bazel.) Force remote execution. Sometimes, non-determinism is inevitable or really hard to avoid (e.g. if you use the Foreign CC ruleset). Under these conditions, your best bet is to force the problematic actions to run remotely under a strictly controlled environment and to provision the remote cache so that such actions “never” fall out. If done correctly, this will “hide” the non-determinism because, once an action has been built, it will never be rebuilt again until its known inputs actually change. Sanitize the action’s environment. Use and to keep settings like the consistent across machines, and use to minimize the environment variables that leak into action execution. Think about network access. If you must, do it from repo rules and always verify that whatever you downloaded matches known checksums. If you are strict about checksum validation, you’ll still have a non-hermetic build, but at least, you’ll have a deterministic one. If you have such behavior in a test, don’t allow its results to be cached by means of the tag. And with that, it’s time to conclude until the next episode on remote caching. Remeber: this is the first part of a series! Subscribe to Blog System/5 now to not miss out on the next one. This article is the first in a series on Bazel’s execution model. Having explained these concepts many times, I want to provide a detailed reference before explaining a cool solution to a problem I recently developed at work. We will start with action non-determinism, then cover remote caching and execution, and finally, explore the security implications of these features. This first article explains what non-determinism is, how it manifests, and how you can diagnose and prevent it in your own builds. Let’s begin. Bazel execution basics Consider the following example build file: This build file specifies two targets : the target, which builds a C library from two source files, and the target, which builds a C binary from one source file and links it against the library. These two targets instantiate the and rules by binding them to specific attributes (the values of and ). Processing these rules during dependency analysis yields a collection of actions : The rule used to define the target generates: A action to compile the file into the object file. Its command line may be: “ A action to compile the file into the object file. Its command line may be: “ A action to link and together into the archive. Its command line may be: “ The rule used to define the target generates: A action to compile the file into the object file. Its command line may be: “ A action to link and together into the executable. Its command line may be: “ The command line to execute , which in this case is . Hashes of the input files required to execute the command. These include “obvious” inputs like the source files specified in the targets but also the files required to execute the tools of the action (e.g. the compiler’s own files). In this case, the list of input files could look like: , , and . The configuration of the environment in which the action runs. This includes environment variables, the host and target platforms, and things like that. In this case, the configuration could include the value of and whether we are building in debug or optimized mode. Configurations are expressed as a hash, though, because of the many details that go into computing them. Date and time. You might not be calling , but build tools—especially code generators and archivers like zip—love injecting timestamps in their output files. These may be obvious, like comments in generated files, or subtle, like values written in binary metadata headers. System identifiers. Similarly to “current date”, there are tools that query the current PID, UID, GID, etc. and inject those values in their outputs. Sort ordering. Hash tables are the star data structure in computer science and they are everywhere. Unfortunately, there are tools that leak their internal use of hash tables into output files by, for example, emitting unsorted lists. Accessing the network. Just don’t . Unexpected/unknown dependencies on host tools. Calling a tool from the system means introducing hidden dependencies on whatever the tool itself depends on. For example, the tool might read a configuration file that alters its behavior. Dynamic execution . This powerful feature that helps improve incremental build times in interactive scenarios can easily lead to non-determinism if the remote execution environment and the local execution environment aren’t equivalent (where equivalent is tricky to define). Foreign CC rules . Bazel tries to enforce action determinism as we saw earlier, but other build systems make little efforts to do so. If you end up nesting build systems, as is the case when using this ruleset, it’s very likely that you are introducing non-determinism. Randomness. Tools can decide to read from and do something with that value, in which case you definitely have non-determinism. Set up a CI pipeline that identifies new instances of non-determinism . Unless you are proactive about it, non-determinism will creep back in because neither the local sandbox not remote execution can fully prevent it. Keep the local sandbox enabled. It may not be perfect but it’s much better than nothing. Also, enable explicitly because, for historical reasons, the sandbox did not forbid network access and the default hasn’t been flipped yet. Rely on hermetic toolchains. Do not use the system-provided ones because they tend to have dependencies on system-provided files that are invisible to the Bazel action definitions. (E.g. if you use the host-provided , the compiler will happily embed into the final binary and this will be invisible to Bazel.) Force remote execution. Sometimes, non-determinism is inevitable or really hard to avoid (e.g. if you use the Foreign CC ruleset). Under these conditions, your best bet is to force the problematic actions to run remotely under a strictly controlled environment and to provision the remote cache so that such actions “never” fall out. If done correctly, this will “hide” the non-determinism because, once an action has been built, it will never be rebuilt again until its known inputs actually change. Sanitize the action’s environment. Use and to keep settings like the consistent across machines, and use to minimize the environment variables that leak into action execution. Think about network access. If you must, do it from repo rules and always verify that whatever you downloaded matches known checksums. If you are strict about checksum validation, you’ll still have a non-hermetic build, but at least, you’ll have a deterministic one. If you have such behavior in a test, don’t allow its results to be cached by means of the tag.

0 views
Blog System/5 1 years ago

Lessons along the EndBOX journey

About six months ago, during one of my long runs, I had a wild idea: what if I built an OS disk image that booted straight into EndBASIC, bundled it with a Raspberry Pi, a display, a custom 3D-printed case, and made a tiny, self-contained retro BASIC computer? Fast-forward to today and such an idea exists in the form of “the EndBOX prototype”! This article isn’t the product announcement though— that’s elsewhere . What I want to do here is look back at the Blog System/5 articles I’ve written over the past months because what might have seemed like scattered topics were actually stepping stones toward the EndBOX. Let’s look at what I learned along the way and why, even though developing EndBASIC may sound like a “useless waste of time”, it’s a great playground and the source of inspiration for the articles you’ve come to appreciate here. You know what to do. Take a moment to subscribe and support Blog System/5! “Porting the EndBASIC console to an LCD” On April 26th, 2024 TL;DR: The article starts with an introduction to EndBASIC’s console framework and how I refactored it to separate display rendering primitives from higher-level operations. This design was inspired by NetBSD’s wscons, and the text explains how so. After that, the article continues to show how to extend the redesigned interface to talk to an SPI-attached LCD, how the SPI communication works, and how double-buffering and damage tracking allow for fast rendering performance. Relevance: This is the article that started the EndBOX but I didn’t know it at the time. You’ll notice that the article ends with a list of parts to build your own embedded box… but because the software wasn’t readily available as a downloadable SD card image, I haven’t heard of anyone trying to use it at all. Lessons learned: SPI bus access: I had to reverse-engineer the sample C code that came with the ST7735s LCD, figure out how to access the SPI bus from Rust, and re-implement parts of it in my own terms. I also had to learn about DTB overlays because the SPI bus is disabled by default. I did not have to dive deep into DTBs at this point, but that came to bite me later. Rasterization algorithms: Up until that point, EndBASIC had leveraged the SDL library and HTML canvas elements for graphics rendering. But when writing directly to an LCD… the only thing you can do is poke pixels. So I had to read on Bresenham’s line algorithm and the Midpoint circle algorithm , implement them and, of course, find a way to write unit tests. “Revisiting the NetBSD build system” On December 28th, 2024 TL;DR: The article presents a general overview of how the NetBSD build system shines in achieving cross-platform, cross-architecture, and root-less builds. Relevance: I had to get back into NetBSD after many years of not touching it because its cross-building features were key to getting EndBOX up and running. Lessons learned: Not much has changed: This is more a realization than a lesson, but it was good to see that not much had changed since I used to use NetBSD on a daily basis. This is good because it shows how resilient BSD systems are, but also bad because some problems that made me leave NetBSD are still present. NetBSD is still unique: I don’t know of any other OS that supports cross-building as trivially as NetBSD does, much less without requiring root access to generate disk images. I hear FreeBSD 15 will sport these same features, and that’s exiting, but “I’ll believe them when I see them”. “Self-documenting Makefiles” On January 10th, 2025 TL;DR: This article is a hands-on tutorial on how to write s that provide help messages by scanning their own content. Relevance: I had read about this idea before but had never put it to practice. In developing the EndBOX, I had to create a rather complex to glue together the patching of the NetBSD tree, the build of the NetBSD toolchain and release, the cross-compilation of EndBASIC for aarch64, and the bundling of all pieces together into a final disk image. Lessons learned: Fragility: Implementing this idea is simple, but in the discussions that followed the article publication, I realized at least two problems: trailing space in variable assignments in is meaningful and this approach cannot easily work if you have includes in your s. Not a big deal for my use case, but having practiced this, I know when and when not do retry this in the future. Use make and you’ll have a bad time: Nothing surprising here, but getting the to orchestrate all these disparate builds and to do it correctly without spurious rebuilds has been painful. What’s worse is that the resulting build process takes a long time because is unable to properly parallelize all build steps. It hurts to see my 72-core server “stall” when a script runs. “Hands-on graphics without X11” On January 17th, 2025 TL;DR: This article presents a deep dive into NetBSD’s console drivers and how those can be used to render graphics directly to the framebuffer without relying on X11 or Wayland. Relevance: Figuring this out was the key to unblocking the EndBOX project. I had built an earlier prototype of the OS image that used EndBASIC’s SDL console over X11 but… the boot times were atrocious and I wasn’t sure I could make them better. Researching how to leverage the framebuffer removed this roadblock as I could get graphics rendering almost immediately after the kernel finished booting. Lessons learned: wsdisplay and wskbd APIs: I had looked at the internals of these devices in the past but never paid much attention to the versatile APIs they expose. I had to do this now, and it was insightful. gdb scripting: Nothing new (I knew this was possible), but I think it was the first time I put it into practice… for the article’s sake. “ioctls from Rust” On February 13th, 2025 TL;DR: An overview on what ioctls are and how to invoke them from Rust when bindings don’t yet exist for them. Relevance: This was a direct follow-up to the previous article: that one was focused on gaining access to the framebuffer, which I prototyped from C, and this one was about productionizing those prototypes in the form of a Rust backend for EndBASIC’s console abstraction. Lessons learned: ioctl formats: Not all ioctls are the same. Some deal with simple data types whereas other deal with large structures—and the way they are expressed is different. Integrating ioctls in Rust: This was “just a matter of programming”, but it was cool to see how the crate makes it easy to expose ioctls in a Rust-native manner so that they just look like function calls. “Hardware discovery: ACPI & Device Tree” On February 28th, 2025 TL;DR: A deep dive on how device discovery works on a modern machine, including details on ACPI and Device Tree, how they differ, and how they are put in memory so that the kernel can read them. Relevance: During the development of the EndBOX, I had to enable SPI to render to the LCD via a DT overlay. I also had to find and install a DTB for the Raspberry Pi Zero 2 W so that NetBSD could boot on this board and so that the WiFi could work too. Lessons learned: ACPI and Device Tree: I pretty much knew nothing about these, so learning about the foundations behind them and how they differ was interesting on its own. Device Tree overlays: I had to write an overlay from scratch to enable the SPI bus on NetBSD—and then get the LCD to actually work (which was its own time sink). Linux vs. NetBSD DTBs: NetBSD reuses Linux DTBs, but NetBSD’s copy is ancient and contains local changes (to e.g. disable the unsupported Videocore). I had to figure out, through sweat and tears, how to port the DTB for the Pi Zero 2 W from Linux to NetBSD without breaking anything else. “Beginning 3D printing” On May 28th, 2025 TL;DR: A beginner-level introduction to 3D printing, including 3D modeling basics, slicing, and actual printing considerations. Relevance: The final step in showing off the EndBOX was to create a case for it that matched the design I had envisioned months earlier. Lessons learned: Unprintable objects: The way 3D printers work imposes constraints on the kinds of items that can be printed, and I had to adjust my design a few times. Modeling vs. slicing: They are two very different things, and I had never imagined that the second existed. It’s not trivial: Even after figuring out the basics, getting a perfect print is difficult. I guess the real world is analog and subject to imperfections. And that’s all for today. If you enjoyed any of these articles, it’s because working on the EndBOX gave me reasons to chase those topics down. To keep this kind of content going, I need time to play, explore, and tinker, so if you’d like to support the journey, please subscribe to or sponsor the project. Sponsor the EndBOX As for what’s next—well, I’m starting to rethink how I can apply the lessons of the EndBOX to something more impactful. Maybe it’s time to turn “just a fun ride” into something greater, because while BASIC may not be the future, the many components that have gone into building EndBASIC and the EndBOX may be. Stay tuned! Subscribe now TL;DR: The article starts with an introduction to EndBASIC’s console framework and how I refactored it to separate display rendering primitives from higher-level operations. This design was inspired by NetBSD’s wscons, and the text explains how so. After that, the article continues to show how to extend the redesigned interface to talk to an SPI-attached LCD, how the SPI communication works, and how double-buffering and damage tracking allow for fast rendering performance. Relevance: This is the article that started the EndBOX but I didn’t know it at the time. You’ll notice that the article ends with a list of parts to build your own embedded box… but because the software wasn’t readily available as a downloadable SD card image, I haven’t heard of anyone trying to use it at all. Lessons learned: SPI bus access: I had to reverse-engineer the sample C code that came with the ST7735s LCD, figure out how to access the SPI bus from Rust, and re-implement parts of it in my own terms. I also had to learn about DTB overlays because the SPI bus is disabled by default. I did not have to dive deep into DTBs at this point, but that came to bite me later. Rasterization algorithms: Up until that point, EndBASIC had leveraged the SDL library and HTML canvas elements for graphics rendering. But when writing directly to an LCD… the only thing you can do is poke pixels. So I had to read on Bresenham’s line algorithm and the Midpoint circle algorithm , implement them and, of course, find a way to write unit tests. TL;DR: The article presents a general overview of how the NetBSD build system shines in achieving cross-platform, cross-architecture, and root-less builds. Relevance: I had to get back into NetBSD after many years of not touching it because its cross-building features were key to getting EndBOX up and running. Lessons learned: Not much has changed: This is more a realization than a lesson, but it was good to see that not much had changed since I used to use NetBSD on a daily basis. This is good because it shows how resilient BSD systems are, but also bad because some problems that made me leave NetBSD are still present. NetBSD is still unique: I don’t know of any other OS that supports cross-building as trivially as NetBSD does, much less without requiring root access to generate disk images. I hear FreeBSD 15 will sport these same features, and that’s exiting, but “I’ll believe them when I see them”. TL;DR: This article is a hands-on tutorial on how to write s that provide help messages by scanning their own content. Relevance: I had read about this idea before but had never put it to practice. In developing the EndBOX, I had to create a rather complex to glue together the patching of the NetBSD tree, the build of the NetBSD toolchain and release, the cross-compilation of EndBASIC for aarch64, and the bundling of all pieces together into a final disk image. Lessons learned: Fragility: Implementing this idea is simple, but in the discussions that followed the article publication, I realized at least two problems: trailing space in variable assignments in is meaningful and this approach cannot easily work if you have includes in your s. Not a big deal for my use case, but having practiced this, I know when and when not do retry this in the future. Use make and you’ll have a bad time: Nothing surprising here, but getting the to orchestrate all these disparate builds and to do it correctly without spurious rebuilds has been painful. What’s worse is that the resulting build process takes a long time because is unable to properly parallelize all build steps. It hurts to see my 72-core server “stall” when a script runs. TL;DR: This article presents a deep dive into NetBSD’s console drivers and how those can be used to render graphics directly to the framebuffer without relying on X11 or Wayland. Relevance: Figuring this out was the key to unblocking the EndBOX project. I had built an earlier prototype of the OS image that used EndBASIC’s SDL console over X11 but… the boot times were atrocious and I wasn’t sure I could make them better. Researching how to leverage the framebuffer removed this roadblock as I could get graphics rendering almost immediately after the kernel finished booting. Lessons learned: wsdisplay and wskbd APIs: I had looked at the internals of these devices in the past but never paid much attention to the versatile APIs they expose. I had to do this now, and it was insightful. gdb scripting: Nothing new (I knew this was possible), but I think it was the first time I put it into practice… for the article’s sake. TL;DR: An overview on what ioctls are and how to invoke them from Rust when bindings don’t yet exist for them. Relevance: This was a direct follow-up to the previous article: that one was focused on gaining access to the framebuffer, which I prototyped from C, and this one was about productionizing those prototypes in the form of a Rust backend for EndBASIC’s console abstraction. Lessons learned: ioctl formats: Not all ioctls are the same. Some deal with simple data types whereas other deal with large structures—and the way they are expressed is different. Integrating ioctls in Rust: This was “just a matter of programming”, but it was cool to see how the crate makes it easy to expose ioctls in a Rust-native manner so that they just look like function calls. TL;DR: A deep dive on how device discovery works on a modern machine, including details on ACPI and Device Tree, how they differ, and how they are put in memory so that the kernel can read them. Relevance: During the development of the EndBOX, I had to enable SPI to render to the LCD via a DT overlay. I also had to find and install a DTB for the Raspberry Pi Zero 2 W so that NetBSD could boot on this board and so that the WiFi could work too. Lessons learned: ACPI and Device Tree: I pretty much knew nothing about these, so learning about the foundations behind them and how they differ was interesting on its own. Device Tree overlays: I had to write an overlay from scratch to enable the SPI bus on NetBSD—and then get the LCD to actually work (which was its own time sink). Linux vs. NetBSD DTBs: NetBSD reuses Linux DTBs, but NetBSD’s copy is ancient and contains local changes (to e.g. disable the unsupported Videocore). I had to figure out, through sweat and tears, how to port the DTB for the Pi Zero 2 W from Linux to NetBSD without breaking anything else. TL;DR: A beginner-level introduction to 3D printing, including 3D modeling basics, slicing, and actual printing considerations. Relevance: The final step in showing off the EndBOX was to create a case for it that matched the design I had envisioned months earlier. Lessons learned: Unprintable objects: The way 3D printers work imposes constraints on the kinds of items that can be printed, and I had to adjust my design a few times. Modeling vs. slicing: They are two very different things, and I had never imagined that the second existed. It’s not trivial: Even after figuring out the basics, getting a perfect print is difficult. I guess the real world is analog and subject to imperfections.

0 views