r/javascript • u/alexelcu • Oct 11 '17
JavaScript's Promise is Memory Unsafe
https://alexn.org/blog/2017/10/11/javascript-promise-memory-unsafe.html16
u/Ginden Oct 11 '17
Author found a tricky part in Promise/A+ spec, that's known for at least two years (Node issue related).
Bluebird doesn't exhibit this behaviour (test code) and keeps steady 58MB memory usage on my laptop.
5
11
u/1-800-BICYCLE Oct 11 '17 edited Oct 11 '17
For starters, return await loop should be return loop. No point in useless rewrapping.
Secondly, I suspect the reason why your Funfix implementation works and native doesn’t is because native promises (and possibly even setImmediate) use the microtask queue and not the event queue. The microtask queue fills and empties before the next turn of the event loop, so if you’re constantly filling the queue with promises to be resolved, chances are that it’s never getting out of that turn. If my theory is right, you’re basically creating an infinite loop (edit: or an infinitely linked list of promises) in the microtask queue.
That said, the solution here has always been to unchain the tail call with setTimeout (yes, setTimeout, not setImmediate or process.nextTick) . Note that your loop here never ends, so you’re effectively only using Promises for side effects and therefore don’t need to chain them at all.
5
u/alexelcu Oct 11 '17 edited Oct 11 '17
For starters, return await loop should be return loop. No point in useless rewrapping.
That is correct, but my primary test has been with the plain function using
then, precisely to not make mistakes like this. It makes no difference though.the solution here has always been to unchain the tail call with setTimeout (yes, setTimeout, not setImmediate or process.nextTick)
I know what you're referring to, but your intuition here is not correct. I updated the article to use
setTimeoutand now it crashes even faster, managing to only go through ~ 1,000,000 iterations before it chokes.What ends up happening is that the code is creating a chain of promises waiting on each other for completion. So it creates
f1, which waits onf2, which waits onf3, creating a long chain ofresolvecallbacks being registered for triggering once the last promise is complete and since that never happens, the heap eventually blows up.What I did in Funfix to fix it, is to indicate to newly created futures (in
flatMap) that they need to complete the source, doing a sort of chaining in reverse. See the implementation.And so what this does is to effectively drop intermediate future references, leaving directly accessible by the GC only the future reference you're holding on to and the active future. And so it ends up using constant memory.
Note that your loop here never ends, so you’re effectively only using Promises for side effects and therefore don’t need to chain them at all.
It's just a simple example to illustrate a point.
You can imagine a stream of tasks processed one by one, where the results are folded into a final result that doesn't have to be
void.Yes, promises get used for triggering async side effects, but many times you also want to aggregate a result as well and having your process blow up only after ~1,000,000 items or so is a big surprise, at least to an FP developer like myself, given that these are asynchronous calls that shouldn't have such problems.
5
u/1-800-BICYCLE Oct 11 '17
Aw shucks, I thought that would fix it. For the last part, though, what I meant was (sorry, I had just woken up lol):
function loop(n) { return signal(n).then(i => { if (i % 1000 == 0) console.log(i) setTimeout(loop, 0, n + 1) }) }Or maybe even
function loop(n) { return signal(n).then(i => { if (i % 1000 == 0) console.log(i) loop(n + 1) }) }You can still sequence and aggregate the results without explicitly chaining the Promise object. I believe that libraries like bluebird do have this same flapMap optimization you’ve created, though (but I’ve started to prefer native for less dependencies).
5
u/alexelcu Oct 11 '17
I have not tried Bluebird, maybe it does it because the problem and the solution are pretty obvious, which is why I was surprised to see that the standard Promise doesn't do it.
5
u/1-800-BICYCLE Oct 11 '17
https://github.com/nodejs/node/issues/6673
You can read about the rationale there — seems to be an issue with either the Promise/A+ or ES6 spec.
3
1
u/SaabiMeister Oct 11 '17
I believe the memory consumption comes from the fact that they keep the functions on hold even if not needed for normal functioning because if an exception is thrown they want to build a stack trace.
8
u/w00t_loves_you Oct 11 '17
Right, but the native await code handles tail recursion properly, no?
Also, did you try this with Bluebird, it might be smarter about forwarding resolutions?
6
u/alexelcu Oct 11 '17
No, that loop using await is not tail recursion and the
return awaitsample also crashes.I have not tried with Bluebird. Will do so later, article talks about the standard
Promiseimplementation.2
u/w00t_loves_you Oct 12 '17
Well, thanks for the article, you got a decent amount of downvotes, but this is reddit ;)
This discussion made me realize I am doing this in a task queue because I was assuming TCO, and I am using Bluebird so I lucked out!
15
u/Danmoreng Oct 11 '17 edited Oct 11 '17
I dunno...tried it Chrome and it didn't crash yet. Gets slower and uses 2.2GB of memory, but still runs:
https://i.imgur.com/t5iDB3S.png
Oh nvm, now it says "Paused before potential out-of-memory crash.", stopping at 4569000.
Wasn't that always the problem with recursive functions in JavaScript though?
https://stackoverflow.com/questions/39898773/pausable-javascript-function/39900192#39900192
2
u/alexelcu Oct 11 '17
It depends on what your memory limit is and it doesn't crash immediately, first the GC freezes the world a few times, freeing whatever memory it can.
12
u/lhorie Oct 11 '17
First of all, I just wanted to say I'm a bit embarrassed to see people getting rude over what is clearly a legitimate, well-isolated, reproducible, and well explained issue. Shitting on other people's work like that is just plain unprofessional. I think whether funfix or bluebird were used as a POC solution should have been irrelevant, and that ideally people should have been eager (or at least open) to learn about the existence of a potential freaking crash and mitigation techniques rather than bickering over the definition of a memory leak.
So I guess the important question is: can the promise spec be fixed?
12
u/andreasblixt Oct 11 '17
To be fair, there's nothing to fix. Yes you can optimize it, but then there has to be made a good argument as to why this is needed.
As it stands the issue sounds a lot like "I filled an array with the number 0 until JavaScript crashed (out of memory). This is bad, and if only the array was run-length encoded (compressed) to support an arbitrary number of 0's, there would not be a crash.
For both the original issue and my toy array example, yes you can optimize them, but the question becomes: Are there enough legitimate cases of this in the wild to warrant making the standard more complex? I think the answer is no, and there's plenty of room to create custom implementations outside of the spec to work around this issue (like the OP did).
2
u/alexelcu Oct 11 '17
Yes, I think there are enough legitimate use cases in the wild.
you cannot describe any functional programming algorithm involving loops without tail recursion — if folds are used, then folds are described with tail recursion as well
the issue is surprising — you, as a JS developer using JS's
Promisemay be familiar with it, but myself, being primarily a Scala / Haskell developer, I find this behavior really, really surprising, especially since it can be fixedIt's hard btw to explain use cases, as it would go over the scope of a single blog article and should be the subject of an entire book.
But I gave this example elsewhere ... processing really long / infinite streams of events, for which it's really natural to describe algorithms using tail recursions and for which you can't really work with imperative, mutation-based loops.
I gave this sample in another comment:
type Task<A> = () => Promise<A> interface List<A> class Cons<A> implements List<A> { constructor(readonly head: A, readonly rest: Task<List<A>>) {} } class Nil implements List<A> { constructor(readonly error?: any) {} }This data structure is really cheap and effective - being a lazy, asynchronous, referentially transparent stream. But as an exercise to the reader, try describing this function:
function map<A, B>(list: List<A>, f: (a: A) => B): List<B>HINT: if that
Promiseimplementation wouldn't leak, then it would be really easy to do.5
u/andreasblixt Oct 11 '17
I hear you, it definitely would be a nice perk, but you really can't be this focused on such a specific use case. To be able to change a specification safely, you need to consider all general cases.
Promisein JavaScript came from a need to be able to chain asynchronous operations, not to chain asynchronous streams of data into a program like you would in a fully functional language†. For example, look at the implementation offetchwhich is a great example of what the ES standardPromiseenables. Together withasync/awaityou get to write synchronous-looking JavaScript while making things work in a single-threaded environment.If you truly want this optimization to make it in, then a more even-sided argument should be made, not just "I can write code that works, so why doesn't the spec also work". For example, you reference the GitHub issue on the spec in your article, which shows just how much has to be considered in these cases. And it seems to me that only considers the case where a chain of promises completely wrap another promise (so you can eliminate the intermediate promises) whereas your example seems to be about a more complex relationship.
Honestly, I'm not sure the standard Promise can ever completely support what you're asking since there are interoperability concerns to consider (compatibility between different implementations of Promise, which the spec supports).
So to repeat, I think it's great you implemented a solution to your problem as someone who comes from a functional language. This will be helpful to others in the same situation, and you can also write an article about how you can write applications that operate on asynchronous streams with this library. But an article about changing the spec would require a much more general argument.
† Sidenote: I don't think the "surprising to Haskell users" argument is very relevant since the vast majority of JavaScript developers come from different backgrounds than functional programming. You will often find that adopting a new language requires you to think differently from whatever language you were using before.
2
u/alexelcu Oct 11 '17
This is a good argument, thanks for it.
I disagree about the need for this, because one use-case of going async is to escape the limitations of the call stack, but I understand from where the philosophy comes from. And I can't be really wrong, given that actual TCO is coming to JavaScript, being part of the ECMAScript 6 spec.
I do believe that FP is even more relevant in the context of JavaScript due to its asynchronous nature and thus potential for non-deterministic results (although less worrisome than on top of a platform that also does shared memory concurrency, like Java).
I also understand the concerns expressed by people on that issue. But there are several implementations in the wild that have been used successfully, at scale I might say, without users hitting gotchas, whereas such a memory leak can be a big gotcha.
Implementations include Scala's Future, in the wild since 2013 (which was my inspiration) and Twitter's Future, which they've been using within their whole infrastructure, in Finagle, etc. I deeply believe this is the right approach.
5
u/lhorie Oct 11 '17
the question becomes: Are there enough legitimate cases of this in the wild to warrant making the standard more complex
Yeah, that's a great line of reasoning. Personally I would prefer that the solution be a native one, and I feel that if bluebird is able to get away with its optimization, it should theoretically be possible to amend the spec, or at least get vendors to agree to make the optimized implementation the de-facto standard. Admittedly, I haven't dug too deep into this yet.
4
u/1-800-BICYCLE Oct 11 '17
From going down this rabbit hole before, I think the main issues are:
Assimilating an old Promise (or Thenable) into a new Promise without maintaining a reference to the old Promise is easy IF both Promises came from the same implementation. This is because the Promises need to be able to look into each other’s internal states in order to assimilate. Since one point of Promise/A+ was interop, it’s potentially spec-breaking to force an implementation detail like this.
There are potential GC issues when different segments of a recursive Promise chain are held by different variables.
The Promise/A+ folks have certain tests to guarantee resolution order in all kinds of edge cases, and implementing TCO seems to break that.
The ECMAScript use of the Promise/A+ spec complicates things further since now there’s another layer of approvals etc. that needs to happen for what, effectively, is an edge case with documented workarounds.
And my own spin on it:
There seems to be a major force in the JS community that wants to maintain Promises as a 1-for-1 asynchronous analog of sync code. This makes sense from the perspective of the async/await API. Just as infinite recursion will exhaust the stack, infinite Promise recursion will exhaust the heap. Perhaps, if TCO is ever shipped for sync code, it will also be shipped for Promises.
13
u/lachlanhunt Oct 11 '17
I tried that code in node 7.10.1 and 8.6.0. It didn't crash at all. It just endlessly printed numbers until I killed it.
11
u/alexelcu Oct 11 '17 edited Oct 11 '17
Proof:
$ nvm use v7.10.1 $ $ node --version v7.10.1 $ node bench.js ... 2360000 2361000 <--- Last few GCs ---> [21305:0x104000000] 52690 ms: Mark-sweep 1408.5 (1467.0) -> 1408.5 (1436.0) MB, 1840.4 / 0.0 ms (+ 0.0 ms in 0 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 1840 ms) last resort [21305:0x104000000] 54684 ms: Mark-sweep 1408.5 (1436.0) -> 1408.5 (1436.0) MB, 1993.3 / 0.0 ms last resort ... FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memoryAlso see a screenshot of Activity Monitor showing the process taking 1.5 GB of RAM.
If you try that in Chrome, it will crash faster, as Node.js is less conservative being configured for the server-side, so what happens is that the process first grinds to a halt, with the GC desperately trying to deallocate memory.
Cheers,
1
u/cwmma Oct 11 '17
I wonder if it has to do with async stack traces
8
u/alexelcu Oct 11 '17
No, it's simply
Promise's implementation.An implementation that works correctly is possible, as can be seen in Funfix's PR, which is a port of the solution implemented by Scala's
Future.
4
u/Onestone Oct 11 '17
Site is down, cached version: http://archive.is/xITge
9
u/alexelcu Oct 11 '17
I'm sorry if that's the case, although the site is up for me: http://downforeveryoneorjustme.com/alexn.org
If it still happens, please let me know and I can activate Cloudflare on it. In general I prefer to not do that for privacy implications – as you'll notice, my website has no trackers, not even Disqus, as they've grown weird lately.
3
u/Onestone Oct 11 '17
Indeed it's up now. It was down at the time of my post.
You could set up a free uptime monitor, e.g. at https://uptimerobot.com/ and get notified automatically if downtime occurs.
2
u/alexelcu Oct 11 '17 edited Oct 11 '17
Thanks for the link, I was looking for a service like that after the free pingdom.com account became more restrictive.
18
u/bair-disc Oct 11 '17
What did I just read?
But before you jump to conclusions, this has NOTHING [caps, OK, smth important is going on] to do with JavaScript's lack of TCO support.
Just guessing that TCO is tail call optimization. What would that exactly do?
This is because in our recursive function it's not JavaScript's call stack that's managing that loop, but rather the Promise implementation.
Loop management by Promise implementation? What does that mean?
That recursive call is asynchronous and so it does not abuse the callstack by definition.
Now we will get our explanation:
Unfortunately, just like a regular function using the call stack for those recursive calls, the Promise implementation is abusing the heap memory, not chaining then calls correctly.
Mhm OK. What has chaining then calls to do with heap memory abuse?
And that sample should not leak, the Promise implementation should be able to do the equivalent of TCO
why, and, again, what does that mean?
and in such a case eliminate frames in the then chain being created.
What? Eliminating frames (which frames? what is a frame here?) because they are created? Eliminating when and why?
This might help:
When a function is called, the computer must "remember" the place it was called from, the return address, so that it can return to that location with the result once the call is complete. Typically, this information is saved on the call stack, a simple list of return locations in order of the times that the call locations they describe were reached. For tail calls, there is no need to remember the place we are calling from – instead, we can perform tail call elimination by leaving the stack alone (except possibly for function arguments and local variables), and the newly called function will return its result directly to the original caller.
1
u/alexelcu Oct 11 '17 edited Oct 11 '17
Just guessing that TCO is tail call optimization. What would that exactly do?
TCO is a pretty standard term and there's available literature for how TCO works that's outside the scope of this article, which is why I linked to Wikipedia.
Loop management by Promise implementation? What does that mean?
It means that the
Promiseimplementation manages the continuation callback and not JavaScript's call stack.Again, there's available literature on how call stacks work or how Promise/Future implementations work, but in case you're inclined to read some source code instead, I think the code that I wrote for Funfix is pretty readable, so here you go, this is what "call management" looks like: future.ts.
Mhm OK. What has chaining then calls to do with heap memory abuse?
Compiler error, does not parse.
What? Eliminating frames (which frames? what is a frame here?)
Promise, and all alternative implementations, are essentially building a call stack, either managed explicitly, or implicitly by means of runtime facilities for doing asynchronous calls (i.e.setTimeout,setImmediateor a thread-pool in Java).But regardless, the effect is that you're substituting one stack representing active call sites for another stack, which keeps track of where the code pointer needs to jump or (in our case) what callbacks need to be called once the result is ready. And in this instance, a "frame" is one such entry in the stack.
This should be taught in computer science, although I've seen lately that universities are dropping assembly programming courses, which is a pitty.
Eliminating when and why?
Eliminating in tail call position because otherwise the process crashes and that makes Jack a dull boy.
11
u/bair-disc Oct 11 '17
But using heap memory and a stack should be an important difference. At least you've said, that Promises do pollute the heap memory, not the (call) stack. It would be nice to consider the difference - or to explain what is meant by abusing the heap memory.
1
u/alexelcu Oct 11 '17 edited Oct 11 '17
There are languages that don't use the stack at all, e.g. Haskell. In the larger scheme of things, the difference is not that big.
What I'm saying is that for functional programming, which helps with reasoning about the ordering of asynchronous / concurrent calls, there's no way to express loops (without mutation) unless you express them as tail recursive calls.
And it's really easy btw to end up with long loops that need to be processed recursively (TypeScript syntax to make the definition clear, but that's irrelevant):
type Task<A> = () => Promise<A> interface List<A> class Cons<A> implements List<A> { constructor(readonly head: A, readonly rest: Task<List<A>>) {} } class Nil implements List<A> { constructor(readonly error?: any) {} }There. I've just described a potentially infinite, asynchronous, lazy, referentially transparent list.
Describing operations on this with
async/awaitor callbacks works, sort of, but it's an exercise in frustration. And by using the Promise pattern as it was meant to be used, you end up with a blown heap.7
u/bluebaron Oct 11 '17
What about this list makes it lazy or asynchronous? Or for that matter, referentially transparent? JavaScript is strictly evaluated, you can't even construct a value in that list unless you have the value to want to add to it already. I see no function signatures indicating callbacks for asynchronous operations either. There's nothing preventing one from mutating one of the references within the list, so I'm not sure where the referentially transparent claim is coming from.
1
u/alexelcu Oct 11 '17
What about this list makes it lazy
The fact that the rest of the stream is described with a parameter-less function, also called a
thunk, which is how you turn strict things into lazy ones, obviously.asynchronous
The fact that the rest of the stream can be processed with a
Promise.Or for that matter, referentially transparent?
The fact that side effects get suspended in that parameter-less function and there's no mutation involved for building it.
I see no function signatures indicating callbacks for asynchronous operations either
That's what the
Promiseis for. If it would work properly that is.There's nothing preventing one from mutating one of the references within the list
I've modified the original definition to have
readonlyon those members, if that makes you happy :-)6
u/bluebaron Oct 11 '17
I missed the
Task<A>you had in the constructor signature the first time, my bad.Also, I know what a thunk is, and your tone in these comments comes off as pretty condescending. I think you'd be better received here if you abstained from talking to people like they have no idea what they're talking about.
2
u/alexelcu Oct 11 '17
I apologize for sounding condescending or aggressive, I do try to explain things using less jargon (
thunkis less understood jargon).I'm also incredibly annoyed. Somebody here called me a scumbag for talking about a library I've been working on in my free time at personal sacrifice, so I don't necessarily know what I'm doing here, instead of going home to my wife and kid, but I guess I'll just pass by the bank first to retrieve my million dollars.
As you can see, my humor doesn't help much either.
Cheers,
0
5
u/PM_YOUR_WORST_FEAR Oct 11 '17
Seems interesting, if you find yourself needing to use infinitely recursive promises.
Say you remove promises from this problem though:
function loop(n) {
const i = signal(n);
if (i % 1000 == 0) console.log(i);
return loop(n + 1);
}
Would you say JavaScript is doing something wrong if it "leaks" when you run that code?
What's the difference here?
5
u/alexelcu Oct 11 '17
The result is that the stack blows up, triggering a stack overflow error.
Yes, it's a mistake, explaining the reason for why is a little difficult, I tried doing that in a comment here.
But also consider that if this wouldn't be a mistake, then they wouldn't be implementing TCO in ECMAScript 6: http://2ality.com/2015/06/tail-call-optimization.html
2
u/Gundersen Oct 11 '17
I didn't get from the article why the promise spec and implementations leak memory. What is it exactly in the spec that requires references to be kept around? I'm guessing it's just a single reference from the new promise to the previous one (or the other way around) that is causing this issue? But for what reason is that reference being kept?
3
u/alexelcu Oct 11 '17
So the problem is that it creates a callback chain. Picture this ...
const p = new Promise(...).then(r1 => { new Promise(...).then(r2 => { new Promise(...).then(r3 => { //... }) }) })If you'll try imagining how an implementation looks like, you'll come up with something like an array on which you
.push()thosethenlisteners, which are going to be executed when the promise will eventually complete.The issue with the chaining above is that:
the first promise (the result of the first
then) will not complete until the second promisedthendoes, so a callback for completing the first promise is kept in the second promisethe second promise (the result of the second
then) will not complete until the third promise does, so a callback for completing this second promise is kept in the third promise...
The problem is that in this chain of 3 promises, the second promise is no longer relevant once it produced
r2so you can simply discard it and if you don't, then it leaks.Therefore a well known solution to this is to reverse the chain. You make the second promise forward its completion state to the first. And the third promise to forward its state to the second and (by compressing the chain) to the first, thus discarding the second.
The problem with the Spec is that the Spec has to guarantee an ordering of operations in certain cases. And by implementing this solution, then ordering changes — not necessarily in a bad way, but the issue is you can no longer rely on the spec alone to tell you what result you'll get, because it ends up being implementation dependent.
So in other words, either all implementations are going to do this, or we can just leave this as semi-unspecified, in which case everybody is wrong, given that some implementations will crash your process whereas others will not.
2
u/Gundersen Oct 11 '17
You should add this part to the article, so it's clearer what the problem is.
Can you also show how the timing of things would be different with an alternative implementation?
I'm guessing a solution/work around is to not return the new promise in each step, since you don't really care about the result. It looks like you only really care about the error?
1
u/alexelcu Oct 11 '17
In my example yes, but I kept it simple to easily reproduce the problem.
Many times however you do care about building a state, folding over the results ... e.g. if you have chunks of data read asynchronously from a file, you might want to gradually analyze it and produce some final result eventually.
Yes, a solution would be to not use return, but many times you need to return, since you need that value. But if you complicate the sample shown, then the origin of the leak gets confusing, so I guess it's a trade-off I haven't hit.
1
u/Gundersen Oct 11 '17
The only real use case for something like this (where it would be an actual problem) is an infinite chain of events, like an async message queue. I've used similar code for that before, without knowing of this memory leak. Letting it run forever in a node app would cause issues.
But now that we (soon) have async iterables it seems less like a problem. They fit much better in those situations, like reading a file and processing chunks of it. I guess promises aren't really designed to be used like this, and while it is a problem now, it's less likely to be one when we have alternatives.
1
u/alexelcu Oct 11 '17
I've included a sample here, refresh to see it: https://alexn.org/blog/2017/10/11/javascript-promise-memory-unsafe.html#concrete-use-cases
What I'm describing is basically an async iterator and I think that even for iterators, it's useful to have a non-leaky implementation because you can then easily describe lazy stream transformations.
78
u/munificent Oct 11 '17
A "memory leak" used to mean memory that had been manually allocated and was no longer reachable. Then folks using GC languages redefined it to mean any memory that was hanging around that you didn't need any more.
"Memory unsafety" means it is possible to misinterpret what a set of bits in memory represent. For example, in C you can cast an integer to a pointer and then try to dereference the result, potentially segfaulting the application.
Now this article is trying to redefine "memory unsafe" to mean, what exactly? That you can allocate lots of memory? Then by that token arrays in JS are not "memory safe":
$ node
> var a = [];
undefined
> for (var i = 0; i < 100000000; i++) a = [a];
<--- Last few GCs --->
16440 ms: Mark-sweep 1373.8 (1403.0) -> 1373.8 (1404.0) MB, 685.4 / 0.0 ms [allocation failure] [GC in old space requested].
17196 ms: Mark-sweep 1373.8 (1404.0) -> 1373.8 (1404.0) MB, 674.5 / 0.0 ms [allocation failure] [GC in old space requested].
17945 ms: Mark-sweep 1373.8 (1404.0) -> 1373.8 (1403.0) MB, 667.3 / 0.0 ms [last resort gc].
18710 ms: Mark-sweep 1373.8 (1403.0) -> 1373.8 (1403.0) MB, 764.7 / 0.0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0xc1e0c2cfb51 <JS Object>
1: /* anonymous */ [repl:~1] [pc=0x14e5000b32af] (this=0xc1e0c2e6ec1 <JS Global Object>)
5: /* anonymous */(aka /* anonymous */) [vm.js:22] [pc=0x14e50009fd28] (this=0xc1e0c204381 <undefined>)
6: sigintHandlersWrap(aka sigintHandlersWrap) [vm.js:96] [pc=0x14e50009ee68] (this=0xc1e0c204381 <undefined>,fn=0x2fb44a970289 <JS Function sigintHandlersWrap (SharedFunctionInfo 0x3acca3663cd1...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
1: node::Abort() [/usr/local/bin/node]
2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
4: v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/usr/local/bin/node]
5: v8::internal::Runtime_AllocateInTargetSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
6: 0x14e4fff079a7
Abort trap: 6That definition doesn't make sense. Promises are memory safe (and do not leak memory either). But you can use them to build a linked list of arbitrary length.
1
0
Oct 11 '17
[deleted]
16
u/swan--ronson Oct 11 '17
We're talking about JavaScript, not C. Definitions change and expand over time. You understand this, we understand this; there is no reason to complain about the definitions to this audience except to berate the author.
Yes, they do change, but within minor boundaries. Memory leaks and memory safety are two different concerns regardless of programming language.
6
Oct 11 '17
This is the expected behavior.
This line means the promise can never be released.
loop(0).catch(console.error)The catch refers to the first promised returned from the loop. That promise "wraps" any subsequent promises that are generated. Every promise in that chain must be kept in order to properly catch the originally returned promise.
In other news, stack exceptions are also Javascript's fault.
1
u/Skhmt Oct 11 '17
type Task<A> = () => Promise<A>
interface List<A>
class Cons<A> implements List<A> {
constructor(
public readonly head: A,
public readonly tail: Task<List<A>>) {}
}
class Nil implements List<A> {
constructor(public readonly error?: any) {}
}Is that javascript?
2
u/alexelcu Oct 12 '17
It's TypeScript, could be Flow, the syntax isn't relevant, I just wanted to make clear what the types are.
Having a static typing background, that's how I think even when working with plain JavaScript.
1
Oct 14 '17
If I understand correctly you expect TCO from a language which don't specify this behaviour.
2
u/alexelcu Oct 15 '17
I expect TCO from a library implementation, not the language, because this can be implemented at the library level and because one reason to go async is to escape the limitations of the call stack.
Also, as mentioned in the article, "proper tail calls" support is coming, having been specified in ECMAScript 6, right now being supported in Safari browsers for MacOS / iOS, so this too will go away.
1
u/Quabouter Oct 12 '17
Thank you for this article. I think this actually happens more than people here believe. In fact: after reading your article I'm quite sure I've actually written this on more than one occasion. Every application has an infinite loop at the top-level, and in non-web settings it isn't uncommon to write this loop yourself (e.g. A game loop). I have written such loops in an async recursive manner (event loops for games and main loops for TUIs), and now that I read your article I think that at least some of them suffer from this issue.
0
Oct 11 '17
[deleted]
-18
u/alexelcu Oct 11 '17
As I mentioned in the article, an implementation that doesn't leak is possible.
So obviously the assertion about creating an "infinitely long promise chain ... means nothing can be GCed" is false.
To see it in action, do this:
npm install funfix --saveAnd then:
import { Future } from "funfix" function loop(n) { return Future.of(() => n).flatMap(i => { if (i % 1000 == 0) console.log(i) return loop(n + 1) }) } loop(0).recover(console.error)This code is doing exactly the same thing, but it doesn't leak.
This is sort of a Stockholm Syndrome btw :-)
6
Oct 11 '17
funfixAh, so this whole contrived example is to push the
funfixpackage you wrote.
Futureisn't a promise. So of course you can write it however you want. You can leave spec behind so you can show you fixed this "terrible" Promise bug by not using Promises.1
u/alexelcu Oct 11 '17
No, the Funfix implementation is there to show that it can be done, otherwise there would be people here saying that it can't be ... oh wait.
Well, I've been called a scumbag for doing self promotion. I guess that if you work on stuff and talk about it, you must be one.
5
Oct 11 '17
I guess that if you work on stuff and talk about it, you must be one.
No. That's not the case. It's how you're coming across in all of this.
You came up with a rather contrived, academic example to demonstrate a very specific problem. Instead of addressing how the specific implementation causes problems, you attempted to generalize it beyond the scope of the issue - including using a clickbait title like "Promises are Memory Unsafe".
No, Promises are NOT memory unsafe and that has been shown time and time again in this thread. In fact, your example isn't even memory unsafe - it's just a fucking infinite loop that causes the program to run out of memory. The exception is thrown because JS can't safely handle memory after it's out of usable memory space.
People are upset with you because they expected you to actually demonstrate how Promises as a whole suffer from a serious memory problem. You didn't and people called you out. You somehow decided that the best approach was to double down on your flawed argument and attack people for criticizing your approach.
-1
u/alexelcu Oct 11 '17
I replied in kind to all technical arguments and added extra explanations where possible, given the limitations of a forum and the time available.
Your argument has a logical inconsistency ... either my linked Funfix is proof that the leak is real and that a fix is possible, or it is not. I also added the following links to that article, for completeness sake:
Now if you have actual technical arguments or opinions, that you can express politely, then we can have a dialog.
1
u/pier25 Oct 23 '17
So obviously the assertion about creating an "infinitely long promise chain ... means nothing can be GCed" is false.
How is that? If you keep a reference to something then it won't be GCed...
This code is doing exactly the same thing, but it doesn't leak.
Well, then it's not doing exactly the same thing. Does it?
1
u/alexelcu Oct 24 '17
There is nothing in the Promise API that says references must be kept in such chains — it's quite interesting how people jump to conclusions on how the implementation should behave, when the API itself is free of such constraints.
In fact intermediate references can be dropped, implementations are known, TFA now includes mentions of such implementations, which are widely deployed and verifiable. TFA also includes acknowledgements from the authors of the Promise spec and others.
And I think I've been pretty clear on that. If not, then let me know how the explanation in TFA can be improved.
0
Oct 11 '17
[deleted]
-9
u/alexelcu Oct 11 '17
All loops in functional programming are expressed as tail recursions, or as folds that are implemented with tail recursions, because otherwise there's no way to express them. And classic loops are inadequate for expressing algorithms involving asynchronous calls, being error prone.
This is not a narrow, edge case, having started with lambda calculus in 1930. It's only an edge case when your tool of choice doesn't support it.
Hence my Stockholm Syndrome joke is really only a half joke ;-)
0
Oct 11 '17
[deleted]
3
u/alexelcu Oct 11 '17 edited Oct 11 '17
It is an edge case to keep around a 2,000,000 promise long chain
The issue is that the implementation should not keep around 2,000,000 promises, being the problem we are talking about. Please re-read what I wrote, because I don't want to keep repeating the same words.
As for why this is an issue, I'm also a little out of breath explaining why, tried to do that in a comment here.
If this is a bug in the implementation ... you should just report it to the v8 team
This isn't an issue with V8, since Firefox has the same behavior, but an issue with the standard.
If it's an issue in the spec you should point out the flaw in the spec and start a discussion about how to fix it.
I was under the impression that I'm doing just that and I'm showing you the solution as well.
you write an article attacking what's become a fundamental part of JS for the purpose of promoting your own library
Well, those of us that are building libraries, we like talking about it. I'm sorry for contributing stuff, I really am, it's a reward-less activity.
It's toxic and my issue is that it does nothing to help anyone except you.
You're attacking me for no reason. My critique was for a piece of technology, yours is personal.
0
Oct 11 '17
[deleted]
11
u/alexelcu Oct 11 '17
So I should just be an angry man that complains about what other people do, but that does nothing about it?
Personally I prefer to show and tell, to build and deliver alternatives and to talk about it. That's not a "scumbag thing to do" in my culture, even if I were to do this for money, which I don't, this being on my own free time and at personal sacrifice.
What about calling people scumbags? Is that appropriate for this or any other community?
We have nothing more to talk about. Have a great life.
1
u/pier25 Oct 23 '17
It is an edge case to keep around a 2,000,000 promise long chain
I agree. Very few people will stumble upon that problem, if ever.
Whether the standard is properly designed to handle such an edge case is another story.
-21
u/alexelcu Oct 11 '17 edited Oct 11 '17
Because my previous post was downvoted to hell, for readers of this toxic opinion, here's some references:
this person calling me a scumbag
Node recognizing this as a spec problem, so it cannot be fixed, along with people experiencing problems in production, see Memory leaks in loops with Promise
Promises/A+ spec issue, the issue still being open, since 2014: chain of never resolved promises create memory leaks
I have also updated the article with these links. Thanks to /u/Ginden and /u/1-800-BICYCLE.
0
Oct 11 '17
[deleted]
3
u/alexelcu Oct 11 '17
Well, it's been opened since 2014. I guess I should go ahead and open a duplicate.
But that might be another scumbag thing to do. Hmm, I'm confused, my moral compass is malfunctioning.
0
Oct 11 '17
[deleted]
1
u/alexelcu Oct 11 '17
I've built no less than 3 libraries implementing the promise pattern, along with Haskell's
IO, a closely related cousin: Monix, cats-effect and now funfix.org (and have in plan to contribute ports to kategory too).If I was right, it was not by accident, this particular topic being an interest of mine for several years actually.
Thanks for enlightening me about the virtues of this community. I've been educated.
0
Oct 11 '17
[deleted]
1
u/alexelcu Oct 11 '17
Oh, was that a question you want an answer for?
Yes, it's been my dream to kill JavaScript's Promise, fragmenting the strong community we have here, lurking in the shadows and waiting for the perfect opportunity. But no, it's not JavaScript's Promise in particular that occupied my time, I just happened to notice it when my process crashed in the middle of the night.
Also, I don't owe you, or the core promise devs or anybody else anything, unless I'm getting paid, so when hearing this reproach, I can't believe it.
Seriously, how low can you get?
0
Oct 11 '17
[deleted]
1
u/alexelcu Oct 11 '17
Yes, promises are chained, but the chaining is flawed, as it should not leak.
Please re-read the article and do a hard-refresh because I've added links to known issues on Node's and the spec's GitHub repositories.
0
Oct 11 '17
[deleted]
2
u/alexelcu Oct 11 '17
In the article I'm linking to my implementation, using what is a standard solution (I do not claim credit), with results that should be easily reproducible (under 5 minutes).
But to your assertion:
Scala's standard Future does not leak
Twitter's Future does not leak
Bluebird I've been told doesn't leak either, being known to be implemented differently
Also in the article I'm linking to the issues created on Node's the Spec's repositories.
You can build one in Java too. Here's Trane.io, built by a Twitter engineer and an acquaintance of mine, although this one comes with a twist - for tail recursivity, you have to defer the thing with a
TailRecobject, but that choice was made specifically for performance reasons.0
Oct 11 '17
[deleted]
2
u/alexelcu Oct 11 '17
perestroika12, how can I say this?
I mentioned 4 independent implementations used at scale, one of them being Twitter's. None of them have the behavior mentioned.
endless future chain
No, it's creating a loop and we are talking about tail call optimizations for these asynchronous
thencalls. The "endless future chain" is the problem, because it should not happen.you have a fundamental misunderstanding of why this is happening and what is going on
I've built Monix, which contains an innovative Haskell
IOport, one of the best in existence actually, along with what I believe to be the best back-pressured Rx Observable implementation. A cancellable future is also in there.Following that, I've built Funfix, which contains IO, Eval and Future, all of which are memory safe. I'm mentioning this in the article, being the reason for why I wrote the article — because I've actually understood the problem and the fix.
And I've helped with cats-effect, being a contributor to cats as well.
If you'll notice there's a pattern in my work, but good or bad, you can't accuse me of a fundamental misunderstanding of what's going on, given that I've implementing the thing multiple times already, with different capabilities and made great effort to work around the problem — which in my case is actually more difficult, because my stuff is also cancelable.
38
u/planetary_pelt Oct 11 '17 edited Oct 11 '17
Hmm, yeah, I guess it's surprising.
But your title is annoying. https://en.wikipedia.org/wiki/Memory_safety
Memory leaks like this are totally memory safe. Further, a memory safe language certainly isn't claiming that memory leaks are impossible in it...
People are going to bring this up every time until you change the title.