Crash on oom strategy

A program is (generally) unusable when it goes out of memory or some other lowlevel disaster happens.
Would it make sense to crash these like this below?
What are ways you people act on these?
I am not talking about critical software but things like games etc.

pub const Fatal = enum {
    mem,
    // other disasters...
};

pub fn wtf(why: Fatal, sender: type, src: std.builtin.SourceLocation) noreturn {
    std.debug.panic("fatal error: {s} at {s}:{d} in {s}.{s}()", .{
        @tagName(why), src.file, src.line, @typeName(sender), src.fn_name,
    });
}

and

const xxx = gpa.alloc(...) catch wtf(mem, @This(), @src());

This would give a quick insight without needing an explicit stacktrace.

it panics, which does provide a stacktrace (unless disabled); you may want to use panicExtra(@returnAddress(), ...) to exclude wtf from that trace.

But yeah, I do a similar thing in some CLI utils I wrote

1 Like

Ah yes. Excluding wtf from the stacktrace would be nice. I’ll check that. Thanks.

I find the following utility useful:

pub fn oom(_: error{OutOfMemory}) noreturn {
    @panic("OOM");
}
4 Likes

That is true. A dedicated one…
I am still fighting with the logic of errorsets.

I have also encountered this question in the past (see What is the best way to handle unrecoverable errors like OutOfMemory in an application?).
What you should definitely avoid is using try, as it tends to make error handling harder when most of the errors are OutOfMemory and you got into the habit of bubbling them all up the chain. (And in essence its no different from crashing anyways)

For Cubyz I ended up maintaining a wrapper around the allocator, that internally panics on allocation failure. However that makes it somewhat clunky to integrate into the standard library at times, I did implement some basics on my own because of that (and because I cannot shed the urge to reinvent the wheel). Though I’m not sure if I would recommend this. Certainly not for smaller projects where the extra maintenance becomes a burden. It does make the code cleaner though, at the cost of extra catch unreachables when interfacing with the standard library.

Depending on the game, it might also be possible to pre-allocate all the memory you’ll ever need, then you wouldn’t ever need to worry about allocation. Though it may not be desirable to set too many artificial limits on things.

I would just challenge that a little. It depends on the program.

For example: A network server runs out of memory whilst serving a particular request. It can crash, or it could dump that request, free all the memory associated with it, and pick-up the next request. It may still be able to serve lighter weight requests, or other threads / processes may free resources.

The biggest problem is you normally don’t get the chance. On Linux, at least, the OOM killer is always lurking and if your memory request fails… he’s coming for ya. You’ll be dead before you know it. You may not even get your error message out.

ulimit is a thing

$ cat example.zig 
const std = @import("std");
test "oom" {
    const foo = try std.testing.allocator.alloc(u8, 1000000000);
    defer std.testing.allocator.free(foo);
    return error.NoOom;
}
$ zig test example.zig
1/1 example.test.oom...FAIL (NoOom)
example.zig:5:5: 0x1270446 in test.oom (example.zig)
    return error.NoOom;
    ^
0 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
.zig-cache/o/4da7116ee48d1b7d1161142c259d3080/test --seed=0xd3b8ac8e
$ ulimit -v 100000
$ .zig-cache/o/4da7116ee48d1b7d1161142c259d3080/test
1/1 example.test.oom...FAIL (OutOfMemory)
zig-x86_64-linux-0.17.1/lib/std/mem/Allocator.zig:325:82: 0x1072ff3 in allocBytesAligned__func_113 (std.zig)
    const byte_ptr = self.rawAlloc(byte_count, alignment, return_address) orelse return error.OutOfMemory;
                                                                                 ^

I recommend watching the recent SYCL talk How To Avoid Needy Software by @marler8997 if you haven’t already. The core point is that it’s generally a good idea for “this should never happen” type errors to not have complicated error handling and instead crash. However that crash should have good visibility to you (the developer) so that you know that there’s a problem you need to solve. There’s a lot more to why and how in the talk.

I’ll post (yet again) my couple of helper methods I use constantly in code.

pub fn check(v: anytype) @typeInfo(@TypeOf(v)).error_union.payload {
    return v catch |err| fatal(err);
}

pub fn fatal(err: anyerror) noreturn {
    if (@import("builtin").mode == .Debug) @panic(@errorName(err));
    std.debug.print("Fatal error {t}.\n", .{err});
    std.process.exit(1);
}

Usage looks like:

const xxx = check(gpa.alloc(...));

The implementation of fatal should change dramatically based on the application. I liked the suggestion in the above talk for having a pop-up box with a contact e-mail for reporting the issue. I originally took a @src argument, but ended up pulling it out because it was redundant with stack traces.

A few random assorted thoughts:

For my game, I’ve gone all in on “just crash” on all of my memory allocations. It’s a fairly lightweight game, and (as suggested above) it typically actually takes work to get the OS to actually give you an out of memory error. I suspect too many badly programmed applications have such bad behavior from OOM that they put a lot of effort into never giving that error.

If you’re able to contain the memory allocations to initial loading, or level loading, that’s ideal. Initial loading would still probably just crash, but level loading could, eg, push you back to the main menu.

If you’re writing something like photoshop, ideally each operation can be backtracked to before the resources are required. So you don’t crash and lose all of your work. You could also put some code to try save all documents in your fatal function.

For web servers, yeah you want to just return errors to the individual request. If you’re trying to do something heavy duty, I recommend reading up on load shedding, and probably the banker’s algorithm. Better to fail fast and early and keep the request queue length low. Also, lifo > fifo.

That is true. And that is why I put (generally) in my text :slight_smile: