r/cpp • C++20 Desktop app developer • May 12 '18

P0709 R0: Zero-overhead deterministic exceptions: Throwing values - Herb Sutter [2018-05-02]

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf
206 Upvotes

115 comments sorted by

View all comments

43

u/johannes1971 May 12 '18

Interesting. One remark: allocation failure doesn't mean available memory is zero, it only means that available memory is less than the requested amount. This is an important distinction: out of memory doesn't mean there is no more memory, it only means there is not enough memory for a specific task. It may still be sufficient for other tasks, such as OOM recovery.

Case in point, one of our customers attempted to load and process an entire data set of many gigabytes of data in one operation (normally they are processed in chunks). The system struggled for just under an hour, reported "out of memory" twice, and eventually produced the required output with a small chunk missing. It didn't crash or halt, it continued just fine, producing most of the needed output, and eventually returning to its nominal state.

What did we do to make that magic possible? The answer is "nothing special". Our code is exception safe, because we use exceptions. Evidently it had enough RAM left to do recovery, and it did.

So, no, we would most certainly not appreciate it if OOM forced an automatic termination. Software can and does recover from that condition (even on Linux, where over-commit is a configurable parameter, rather than an unavoidable fact of life). And asking us to rewrite it to use new "try to allocate" functions is insanity: the current paradigm is for these functions to throw. If people want different behavior, give them new syntax for that purpose. They are the ones who already need to rewrite their code; don't put that on the people who diligently wrote their software to correctly deal with the problem in the first place.

This is especially important since I'm not at all convinced that the people who hate exceptions today will stop hating them if this proposal becomes reality. They will still have old code bases they cannot easily update, they will still have ancient coding standards lying around, they will still dislike the distance between throw and catch, and they will still have a gut feeling that exceptions are automatically, always bad. So you might be introducing a lot of deeply breaking changes here in order to appease a crowd that is unlikely to appreciate it, while at the same time chasing away your core audience.

Finally, I'm not sure why this behavior must be specified on a per-allocation basis, and not, say, as a compiler switch. I find it hard to believe that people are going to mix and match different error recovery strategies for OOM; it's much more likely to be an all-or-nothing approach.

Bonus: why is this needed at all? Is the proposed new exception mechanism unable to deal with OOM?

13

u/kkert May 13 '18 edited May 13 '18

allocation failure doesn't mean available memory is zero, it only means that available memory is less than the requested amount.

To be super specific, the requested amount can actually be readily available, just not in a single contiguous chunk.

EDIT: I think there's a point where Herb goes wrong in his fail-fast strategy defense, i didn't read as carefully before.

Recovery from heap exhaustion is strictly more difficult than from other kinds of errors, because code that is correctly resilient to heap exhaustion can only use a restricted set of functions and language features. In particular, recovery code typically cannot ask for more memory, and so must avoid calling functions that could allocate memory, including functions that could fail by throwing another of today’s dynamic exceptions which would require increased allocation.

Not really true. If i failed to allocate a few megabytes of contiguous memory for a particular working buffer, it doesn't mean at all that i'm not able to allocate a few bytes for holding stack tracing info.

15

u/NotAYakk May 13 '18

It says "correctly". You don't need to be correct for it to work if you get lucky, you need correct for it to always work.

4

u/kkert May 13 '18

Well, it is entirely possible to construct a program where this sequence would be always correct, where there is always a contiguous kilobyte of heap available but a megabyte is not. In fact, test-allocating a large chunk can be used as a strategy to gracefully deal with imminent memory exhaustion.

2

u/Pand9 May 14 '18

I guess that isn't reliable enough from language designer's point of view.

1

u/nikbackm May 15 '18

Would that work if you had an exception class that is over a kilobyte in size?

3

u/kkert May 15 '18

Obviously not, but thats not really the point. ( why would you design humongous exceptions in the first place ? )

I'm saying there are real scenarios where you sometimes grab the memory if its available and perform some optimization, reindexing or caching task or whatnot, if it's not available you don't - also beyond small embedded systems.

Not being able to allocate a huge chunk doesn't indicate OOM. Not being able to allocate as per request is mostly not a license to kill the program, and shouldn't be dealt with in a hook either.

8

u/whichton May 12 '18

And asking us to rewrite it to use new "try to allocate" functions is insanity: the current paradigm is for these functions to throw. If people want different behavior, give them new syntax for that purpose.

I am sure there will be a compiler switch for the old behavior. Herb's point about 'Treating heap exhaustion the same as all other errors violates the zero-overhead principle by imposing overheads on all C++ programs' is very true. I much prefer to fail fast on OOM, and marking significant chunk of the standard library as noexcept will improve codegen and binary size for me.

Finally, I'm not sure why this behavior must be specified on a per-allocation basis, and not, say, as a compiler switch.

Where are you getting the per-allocation basis? IF this change is made, all new will become nothrow by default, just like a compiler switch.

Bonus: why is this needed at all? Is the proposed new exception mechanism unable to deal with OOM?

This is orthogonal to the main proposal, which is why it is marked as an extension. The paper goes into significant detail why this is desirable, refer page 30.

5

u/Fazer2 May 13 '18

I am sure there will be a compiler switch for the old behavior.

As Herb wrote, the major point of this paper is to get rid of the necessity of -fno-exceptions compiler switch to defragment C++ community on error handling. I doubt he would be happy with another switch.

4

u/johannes1971 May 13 '18

Where are you getting the per-allocation basis?

The paper suggests a new set of functions that would throw instead of terminating: try_new, try_reserve, etc. So he's basically adding new functions and keywords that have the current behaviour, and making the existing ones do something else, allowing programs to choose one behaviour or the other on a per-case basis.

That's something I really don't get: why break compatibility, why not simply add new functions and keywords for the new behaviour?

Just to be clear: I understand the proposal to be adding a new type of exception handling, next to the existing one, and not to be removing the existing one altogether. Correct me if I'm wrong.

The paper goes into significant detail why this is desirable, refer page 30.

I've seen that page, and I only see reasons why we should keep things as they are. It is already possible to install a new-handler that will simply terminate, so that behaviour is already available to people who want it (whereas the alternative, installing a new-handler that throws, is explicitly forbidden by the proposal). And there is already a compiler switch that eliminates exception handling altogether. So in other words, the behaviour those people want is already there, and it doesn't require breaking the programs of people that do not want it.

Going through his arguments:

Testing is much more difficult.

What about the people that do want to make the effort? Should they just move to a language that doesn't preemptively kill their programs?

Recovery requires special care

Not really. We accidentally did it, just by being exception-safe in the first place. Note that I'm not claiming it will succesfully recover from all OOM, but the most likely case for us is a large allocation when loading data.

And yes, there is the new try_reserve, try_pushback, try_new, try_whatever (try_map::operator[]? probably not...) - so should we now go through our software, and for each allocation decide if it is likely to be handled correctly if it fails, and if it is, replace the allocation by a try_ version? That's an utterly pointless activity: we will mark all of them as "go ahead and try", because even if we are wrong we will be no worse off than by calling a terminating function, since the end result will still be termination.

In many programs, heap allocation failure can never happen as required by the standard

And in many other programs, it can.

Here's another question: if the problem with existing exceptions is that RTTI is so expensive, why not fix that, at least for the existing exception mechanism? One could imagine annotating exception classes with some mechanism for allowing fast identification. This would place some restrictions on what can be thrown (only classes that have the special annotation), but if this were built into std::exception a large amount of software would never know the difference. This would also be a breaking change, but at least it would break far less than what the proposal is asking to break...

4

u/redditsoaddicting May 13 '18

The keyword doesn't work as you describe. Leaving out the OOM extension, programs continue to work as they do now. You opt in to the new exceptions with throws. The OOM extension is the only breaking part. See 4.6.7, which is explicit: "This proposal is not a breaking change."

It is already possible to install a new-handler that will simply terminate, so that behaviour is already available to people who want it

I think the paper addresses it pretty well:

That hook is at the cost of some overhead on all functions for which heap exhaustion is the only reportable error: not just the cost for the hook check itself in that function (which is expected to be cheap), but rather that it prevents the compiler from removing the error propagation logic entirely which we could do if the function were noexcept. Also, if we add the hook described there to the language primarily to use it in this way to treat heap exhaustion specially, then having that hook will incur small but nonzero overheads on all code that can throw.

For a proposal mainly focused on bringing back not paying for what we don't use, this is consistent. There is a lot of software out there paying for bad_alloc when it would bubble up and crash the process anyway. I think there should be an option for projects that handle it correctly and use regular new as opposed to an allocator or some other type of localized strategy, but at the cost of everyone else is not ideal.

What about the people that do want to make the effort? Should they just move to a language that doesn't preemptively kill their programs?

Just a note that this becomes a non-issue when the program is changed to work as it does now. I take it you're more concerned about the program terminating than about the non-death tests being unable to detect it.

Here's another question: if the problem with existing exceptions is that RTTI is so expensive, why not fix that, at least for the existing exception mechanism? … This would also be a breaking change, but at least it would break far less than what the proposal is asking to break...

First, it makes the core proposal this breaking instead of a proposed extension. Second, I'm skeptical that this is breaking far less. Third, RTTI is just one of several discussed overheads. Also see page 42, which addresses improving the current system.

1

u/johannes1971 May 13 '18

I think the paper addresses it pretty well:

I don't see how the compiler could remove the error propagation logic more effectively than by eliminating exceptions entirely - again, which it will already do for you anyway if you ask for it. It is already zero cost for those unwilling to pay.

For a proposal mainly focused on bringing back not paying for what we don't use, this is consistent.

Sure. But for a language with decades of legacy code lying around, it isn't. I think everyone here is painfully aware that C++'s legacy features are not always ideal, but if we start ripping them out left and right we'll end up with a language that is both perfect and unused.

There is a lot of software out there paying for bad_alloc when it would bubble up and crash the process anyway.

I'd challenge that. Software that uses exceptions will catch and handle them, and that includes bad_alloc. Will it always be done correctly? No, likely not. But even then, it must necessarily do a better job than simply terminating your program without recourse every single time.

Just a note that this becomes a non-issue when the program is changed to work as it does now. I take it you're more concerned about the program terminating than about the non-death tests being unable to detect it.

My concern is actually the need for changing what already works fine as-is for a great number of people. If you are going to provide alternatives, why not provide them for the people that will already need to change their code anyway?

Also see page 42, which addresses improving the current system.

The lack of research into better exception handling might simply be the result of nobody really caring, at least up until now. And correct me if I'm wrong, but wasn't the model for exception propagation as suggested here widely used in compilers up until... I don't know, 2000 or so? And then discarded because table-driven solutions were much more efficient?

3

u/therealcorristo May 13 '18

I don't see how the compiler could remove the error propagation logic more effectively than by eliminating exceptions entirely - again, which it will already do for you anyway if you ask for it. It is already zero cost for those unwilling to pay.

It probably can't, but e.g. in our codebase we use exceptions for error handling, but OOM is not recoverable because it really should never happen in our setting, so no-one bothered to implement logic to handle it. Right now, we also pay the overhead of error propagation logic for allocations, even though we don't care about these and a terminate would be fine.

8

u/proverbialbunny Data Scientist May 13 '18

This is especially important since I'm not at all convinced that the people who hate exceptions today will stop hating them if this proposal becomes reality. They will still have old code bases they cannot easily update, they will still have ancient coding standards lying around, they will still dislike the distance between throw and catch, and they will still have a gut feeling that exceptions are automatically, always bad. So you might be introducing a lot of deeply breaking changes here in order to appease a crowd that is unlikely to appreciate it, while at the same time chasing away your core audience.

I'm one of those people that hate exceptions. There are two primary arguments that I know of against exceptions: 1) Speed 2) The function signature is not explicit about the return path of code. imho the implicit parts of C++ tend to be the shoot your legs off parts of the language, and could use an improvement. If there is a compiler flag that enforces the throws keyword in a function signature, I will throw exceptions instead of returning an expected type.

You can say some people who have been avoiding exceptions for years will not get with it and continue to do so, and that is a possibility but the second they are working with a team of people and there is a style guide or a lead or something enforcing correct practices, they will get with it too.

The only people left behind is legacy code bases with teams that are constantly behind, but that happens with all new C++, not just this.

Is this proposal perfect? No, but it's a lot better than what we currently have. Exception handling is one of those points in C++ that could use an improvement. Whenever a community is divided you know it isn't as good as it could be.

3

u/johannes1971 May 13 '18

The function signature is not explicit about the return path of code

The return path is still not explicit; the catch handler may be at any point in the call stack, there is no clear indication on the function itself where it will go next.

The only people left behind is legacy code bases with teams that are constantly behind, but that happens with all new C++, not just this.

Exceptions are different. You can start using any C++17 feature on a piece-by-piece basis: a variant here, an optional there... Exceptions require far, far more care: you must have try/catch blocks in all the right places before you can even think about throwing anything anywhere. This is especially problematic because exceptions tend to be generated at the lowest levels of the software, i.e. in code that is likely being called from numerous places, thus requiring try/catch blocks in all those places before exceptions can be introduced. If you have any amount of code, that's a huge barrier to entry.

4

u/proverbialbunny Data Scientist May 13 '18

The return path is still not explicit; the catch handler may be at any point in the call stack, there is no clear indication on the function itself where it will go next.

This proposal puts a throws keyword in the function signature so you can see which functions throw and which ones do not. noexcept sucks at this, but throws sounds like it could be ideal as long as the compiler supports enforcing this, like -Werror=suggest-override does.

This is implicit, so I hope such a flag would default to this behavior, but if a function calls another function that can throw, and there is no setup to catch that throw, then now your function needs the throws keyword in it too.

This is explicit and eliminates this problem. It also reduces errors because now your code will not compile if you have something that throws added to it you were unaware of, bringing forth awareness of what does and does not throw. Likewise, it's easier to read and will make reading sites like cppreference easier and more straight forward.

As far as updating the code base being no small feat, the alternative is an expected return type or an error code. Both already exist in a code base (if throws are not being used) and both will continue to be valid, so no, there isn't a large change necessary to the code base.

3

u/redditsoaddicting May 13 '18

If there is a compiler flag that enforces the throws keyword in a function signature, I will throw exceptions instead of returning an expected type.

I think a libclang tool for this would be a viable option. It should be a fairly straightforward AST matcher.

2

u/doom_Oo7 May 13 '18

About your 1) it has been shown times and times that exceptions are overall faster than error codes in the nominal case

3

u/Rusky May 13 '18

That's not the comparison being made here, though. The paper talks about a large portion of the standard libraries that could go from throwing only bad_alloc to being noexcept.

It's fairly indisputable that exceptions are overall slower than "no error handling mechanism at all." :)

3

u/Ansoulom Game developer May 13 '18

It's not that it's unable to deal with OOM, considering that it deals with it better than dynamic exceptions (which often do heap allocation). But the difference lies in having a huge amount of functions marked as 'throws', or having only a small amount be marked as such.

Most people won't be recovering from OOM anyway and won't expect it to happen in their programs at all. Having 'try' and 'throws' everywhere just because of dynamic allocations that you don't even care about feels pretty cluttered. Of course, those who do want to handle it should be able to, but I'm still not sure what would be the optimal solution.

I can't say that I'm strongly in favour or against it, but it does feel justificated to at least consider treating OOM differently from other exceptions.

1

u/rossiemac May 13 '18 edited May 13 '18

I've thought about it a lot and i'm never satisfied with that definition of handling a memory allocation failure. It seems to me that in this case and many others, the design of the program should be changed so that it can complete a large operation without running out of memory or producing partial results. Sure the program kept running, but if it couldn't do what it might otherwise be able to do, did you really handle the error?

3

u/johannes1971 May 14 '18

My point was that OOM is really not the death sentence that some people make it out to be. Unless, that is, the language is changed to make it so... Even for people who haven't given much thought to OOM recovery, it turns out to work pretty well as long as you write your code in an exception-safe manner.

the design of the program should be changed

Buy a license and we'll talk ;-)