If you don’t put limits in your code, the hardware will do it for you
I have a hobbyist graphics project. I use an LLM to assist with writing this project. It’s written in RAD-style C++. The thing that continuously keeps my curiosity going is “How do I enforce code correctness in a way so an agent produces code I don’t need to validate?” By “validating” I mean that I still read it, but I don’t intentionally look out for bugs – I want to be reasonably sure that the thing works for cases I don’t test directly.
RAD-style means Arena allocation. An arena is a contiguous region of memory. I have a “MemoryBank” structure – a fixed-size array of arenas. The purpose of the bank is to allow iterating over all arenas allocated in the project to do memory accounting: how much each subsystem uses, track growth patterns to catch leaks, etc.
I have an asset pipeline. It’s multi-threaded code which takes assets (geometry data, textures, etc.) and processes them to a format the engine can use. I use a meshlet pipeline, so I need to transform geometry to meshlets to render it. I also want to compress textures, etc.
I want to be able to run this asset pipeline during scene authoring in the engine. The issue is that the asset pipeline operates on files of variable sizes in a multi-threaded manner. So given a fixed-size memory bank the asset pipeline can utilize all the memory available and fail loudly because the code is not built to handle the “there are no arenas available” case.
The important nuance here is that since it’s a background job, the allocation failure can happen far away from the original cause. The UI layer allocates memory from the bank each frame to build an immediate mode tree. If I want to handle allocation failures in one subsystem, I need to handle them in every subsystem in the frame path.
The first obvious thing I tried was making allocations fallible and handling each failure separately. 98% of the code (think of UI code) uses hundreds of kilobytes at best. Even with a complex UI frame with thousands of widgets, each widget is <1kb and the total memory used is in the lower tens of megabytes – it’s not the thing causing failures. So allocation failure handling for those 98% would practically never be exercised in reality.
Another issue is that even if I decide to bite the bullet and propagate allocation errors from every subsystem the project uses, there’s not much I can do about them, because the error itself doesn’t tell me which subsystem uses most of the available memory. The natural thing is to show an error to the user, but a) I need to do that without allocating – this issue is familiar to anyone who has tried to handle memory failures, and b) I can’t show the reason for the issue with any certainty.
Taking a step back
One of the reasons I started doing graphics as a hobby is open-world games. The combination of engineering and art used to construct artificial places which affect how I see the world – something about the whole thing mesmerizes me. The question which originated this curiosity sounds like this:
How do open-world games create an illusion of a world without boundaries, given that the world itself doesn’t fit inside the capacity of the hardware I use to play them?
The straightforward answer to that is streaming. The software used to present those worlds does its best to hold only the stuff you see immediately on the screen and then constantly loads/unloads different parts of it in the background to create the illusion. The really hard part is to figure out what you’re going to see in 5 seconds – basically, predict the future – to start loading that part before you even look, so you wouldn’t see an illusion-breaking “loading” indicator or visual glitches.
This is where the notion of a budget comes from. The hardware has a limit – maximum number of bytes per second you can transfer from e.g. disk to gpu. Another number from a much higher abstraction layer is maximum allowed player speed. Since it’s a game, it’s designed to be played in a specific way, and changing the player’s experience based on the speed of their SSD is a very questionable approach to game design.
And those two numbers – player speed and disk throughput – meet in the middle. The artists authoring the world design it in a way so that any given part of this world can be traversed without glitches. Imagine a map of your favourite open world game, and then imagine that for any given square meter you calculate a density of this region. The density is how much detail it has – how many textures are used, triangles to draw the geometry, etc. The assets are streamed and the player can only traverse a limited number of those regions per second, and the number of “region” load/unload operations must fit into the limit the hardware allows.
The budget is very important and usually set very early in the project, because if you change it after you start designing the world itself, you either need to redesign everything you’ve done already or the world wouldn’t feel consistent.
The solution
The generalization: instead of trying to handle “resource is out of capacity” errors, pick a number and then decide what happens if the number is reached. Generally, the following options are available:
- Evict least recently used members (LRU caching)
- Say “submission failed” to the code using the subsystem
- Don’t communicate anything to the outside world, just ignore the submitted entry
- Clamp – use lower quality data, e.g. lower the level of detail for a given mesh.
Given that the implementation encodes this number and picks the strategy, the natural next step is to pre-allocate everything.
It simplifies the implementation by a huge margin. Instead of asking an agent to write a thing which behaves correctly both under normal circumstances and under memory pressure, there are only two cases to handle: code before the limit is hit and code after. And since the limit is externally provided, it’s trivial to write a unit test which sets e.g. max_gui_widgets = 8 and checks that the UI still builds, although partially.
“That increases resident memory usage,” you might object. Most of the time I don’t care about the additional 700 kilobytes allocated for GUI widgets. I care about the GPU memory budget, because the engine handles hundreds of 2k textures (16mb each) with gigabytes of geometry. I want to focus on the parts which draw actual pixels on the screen, not to hunt for UI bugs.
The second part of the insight is “different limits depend on each other”. Here’s another example.
To render fonts in the UI, I rasterize them to a bitmap and use it as a texture for tiny rectangles on the screen. The rectangle references the region of the bitmap with the glyph I want to render. Since there are many languages with many different glyphs, and usually the user wants only a subset of them, LRU is used. But the maximum capacity of the LRU can be derived from two existing limits I want for unrelated reasons:
- Maximum rendering resolution – to guarantee a smooth experience for the player.
- Minimum size of the font – to spare myself from designing UI layout for a font size of 1px.
Given those two numbers and “UI submits only visible glyphs to GPU” – a property which can be enforced with a unit test – the LRU capacity is maximum resolution / minimum size of a glyph rectangle.
So how does it solve the original issue? Since I declare the limits for everything, assets are no exception – given maximum file size, texture size, etc. I can replace the “pipeline must handle everything” implementation with a streaming one. And if the pipeline reaches the limit, I know the UI can render something like “the asset pipeline failed because file N is bigger than allowed” because all UI widgets are reserved upfront – every subsystem reachable in the frame rendering path is bound.
An interesting bit of counter-evidence to increased resource usage – the limits are often already in the code, since somebody made a quick decision like “I don’t need more than 64 UI cache textures”, with the number being almost random, intuitively derived. Two issues with that: those hardcoded constants are rarely updated, because tracking implicit assumptions in the codebase is hard. And the numbers are often a “safe upper bound”, not an actual computation derived from what the system is supposed to do.
To express this dependency in code, I defined a limits.hpp file:
struct Limits
{
Limits_GUI gui;
Limits_FontCache font_cache;
Limits_Rendering rendering;
Limits_Assets assets;
Limits_Scene scene;
// ...
};
struct Limits_Resolved
{
Limits_GUIResolved gui;
Limits_FontCacheResolved font_cache;
Limits_RenderingResolved rendering;
Limits_AssetsResolved assets;
Limits declared;
};
// The one place a limit is derived from another subsystem's limit. Asserts the
// relations it rests on, so an app that declared a zero finds out here.
Limits_Resolved limits_resolve(Limits const &limits);
So during application startup, I define a bunch of numbers, call a function which does sanity checks, and initialize every runtime subsystem with knowledge of the maximum number of elements it should handle.
Since during development I want to tune those numbers, I also want to know if the subsystem hit its limit at runtime, which is also straightforward: void limits_report_hit(Limits_Kind kind, u64 wanted, u64 available);
Evidence
Case: Rendering complexity
Anyone who has written code using a “modern” (read: anything later than OpenGL) graphics API knows: GPU resources have a very finicky state machine requiring a lot of special handling. Vulkan is famous for being verbose, because the API is very literal about representing this state machine. If you want to upload something from the CPU to a GPU buffer, you need to set the buffer’s state to “uploadable”, issue the upload operation, transition it to “usable in a shader”, wait until the upload finishes via some communication channel, and after that issue a shader call.
The real problems arise once the buffer you’re using isn’t big enough to fit the thing you want to upload. Graphics pipelines usually have more than one frame “in flight”; they pipeline the rendering (hence the name), which means that the resource you’re using might be referenced by the previous frame. For that reason, upload queues are usually double-buffered, meaning that if the pipeline is configured to have two frames in flight, I use two buffers.
And if I want to resize one of them, I need to either a) copy this frame’s uploads into a new one, free the previous one, track the second buffer’s size separately, or b) resize both and defer the deletion of the previous frame’s buffer until at least two frames pass. Given the verbosity of the API above required to track a buffer’s state, this creates a huge amount of complexity which is rarely exercised, because most of the time the buffers don’t grow.
So I pre-allocate all buffers depending on the content itself. This is a deliberate tradeoff – the engine utilizes more resources upfront and doesn’t “adjust” based on scene complexity, but since it’s purpose-built for a single project, I’ll take the simplicity and stability guarantees any day over a more efficient implementation. It doesn’t mean there’s no resizing in the rendering path at all, because some parts are screen-bound, and I don’t want to pre-allocate a 4k depth texture on a GPU which has 2gb of memory. Still solvable by allowing subsystems to re-initialize from a dynamic limit, but during resizes the GPU device stalls anyway, so I don’t care.
Case: Silent infinite hang in the asset upload
The compressed textures are uploaded to the GPU by splitting them into rows and walking rows line-by-line. The code responsible for row submission into the current frame’s upload ring never distinguished between “this frame’s ring is exhausted” and “this row can never fit any ring”. Once the maximum texture size is set, the limit naturally flows across the codebase making this piece of logic wrong by construction, since the ring size must be greater than the size of any individual uploaded entry – texture row, set of meshlet pages, etc.
Case: Linear hashing
The UI’s two record indexes were a bespoke hash table, written for one property: grow in an arena that is never popped. Linear hashing (Litwin) gets that — buckets are appended, one splits per insert past the load factor, nothing is ever orphaned. Three hundred lines, one user.
Once the widget limit is in, both indices use a pre-allocated SwissTable like the rest of the engine. This provided approximately zero perf difference, because linear hashing converged quickly and low thousands of widgets are a minuscule dataset to handle – the difference was 764us vs. 758us per frame for the UI build, but the real win here is the amount of deleted code that existed for a single user.
Conclusion
This post intentionally doesn’t mention the malloc family and assumes an arena-first codebase. Malloc is the worst case for predictable failures – the contract’s promise is that memory is infinite, and the OS will swap out your pages if you use one too many, without notifying you about it. But this approach doesn’t remove the ceiling policy, it just picks one for you.
There’s a quote from Casey Muratori: “The best way to handle errors is not to have them”. The approach described above is exactly that: instead of holistically finding how much data the system can process, pick a number, pick a strategy describing what happens when the number is reached, assert this behavior.
This approach works independently of LLM usage, but the reason it works so well with assisted coding is that it makes the code simple – it’s hard to beat a statically pre-allocated array with an explicit error strategy.