Hacker News new | ask | show | jobs
by varenc 10 days ago
As others have said, macOS does this by default and it's quite impressive. I have a long running daemon with a memory leak. By its nature, the leaking memory is very repetitive and easily compressed. Right now this daemon has tried to claim 2.5GB of memory, but it's been compressed to a mere 450MB of actual memory! And because it's a memory leak, it never accesses this old stuff, so it never gets decompressed. Only 20MB of RAM is held that isn't compressed.

Of course, it would be far better to just not have the memory leak...but in the mean time, macOS memory compression is making the leak nearly a none issue.

9 comments

I discovered something similar when I tried to recreate a rudimentary version of the Billion Laughs Attack[0] on my macbook. It just compressed all the “ha”s so the 10 GB string only ever took a few MB

0: https://learn.microsoft.com/en-us/archive/msdn-magazine/2009...

I had a similar experience, but with Apple's APFS on-disk file compression! I accidentally generated a log file that just contains 300+ million lines of the same message repeated constantly. The log file was supposedly over 100GB in size, but I hadn't noticed my disk filling up. I investigate more, and discovered that APFS had compressed the file on my disk!

APFS on-disk file compression is very mysterious, hard to observe, and harder to intentionally trigger. The only clue in the Finder GUI is comparing the file size vs size on disk. Using the 3rd party `afsctool` you can tell APFS to compress a file on disk manually, but I believe there's no good native macOS way to do this. The official way is that macOS decides for mysterious reasons when to compress a file on disk and it rarely does. But apparently generating a 100GB log file with million of repeated lines is enough to convince macOS to use APFS compression. (and having a disk that's nearly full probably)

edit: looks like `applesauce` is a more modern tool like `afsctool` that lets you use APFS transparent file compression: https://github.com/Dr-Emann/applesauce

But why? Curious as to the reason. Fascinating though.
oh hah, I’m not a security researcher or anything. I was just a high schooler messing around with computers. The rudimentary version I tried was just doing something like this in the python repl

    a = “ha”
    b = 10 * a
    c = 10 * b
and so on and watching the memory climb in the activity viewer. I was surprised when the 10GB or even 100GB one (confirmed with len() ) didnt crash my 8GB laptop or even cause it to swap.

Interestingly I tried the python version just now on modern macos, currently activity monitor shows 192GB ram used, 184GB compressed, on a machine with 36GB physical.

Actually something really weird happened, zsh killed the python proc, activity monitor shows it still alive, but the physical ram value is bugged and showing 0 bytes physical and 1.7 GB swap. So compressing RAM does have some limitations.

haha!!
A new take on the OOM killer: if a long-running daemon hasn't touched some heap pages for a very long time, perhaps the OS could assume it is leaked and unmap the pages. If the daemon tries to access that memory, let it crash.
This sounds like a bad idea. No one has logged in via SSH for a while so the daemon hasn't touched any pages (or only pre-auth relevant pages) then when you log in it gets killed. Or if someone sends a rarely used request to an HTTP server then it crashes accessing some data unique to that request.

Sure, they will get restarted, but not great.

It's a good example of perverse outcomes. Rather than simply following the contract and functioning correctly, we would be:

going through extra effort to accommodate/enable buggy, poorly behaving programs, and meanwhile—

punishing those (and the programmers of those) that are well-behaved and functioning exactly as intended but that now have to contend with evading some heuristic of badness.

You have described the current state of Android development if you want your app to stay alive and be useful without its GUI in the foreground. It is an insidious process that has essentially broken the OS more with each release, and broken apps that were mindful of battery usage but didn't pull the correct magical levers.
So true.

On my Lenovo tablet there is no working way to get it to allow any app to stay open.

I deliberately bought the version with the most ram, but that was dumb because it never uses any of it because it so aggressively kills apps.

It's unbelievably annoying. I've spent an inordinate amount of effort to try to work around it, but it still regularly kills apps that I want to stay open. Those apps do stay open and work properly on my phone, which has less ram than the tablet.

Fuck you, Lenovo.

Webapps.
Yeah this is the modern trend it seems. There is a potential problem. Add more stuff around it. To the point where you aren't trusted with your own computer.
"All means are fair except solving the problem"
I think what they are saying is if OOM was going to kill the process anyways, it can defer this a bit and only fault on read or write on the rarely used memory.

So don’t change the OOM descision making, just the action taken.

I think my sibling comment makes a good point though, that this encourages or permits buggy code.

OOM triggers when memory pressure is critical; it's not practical to further defer addressing it at that point.
Huh? Defer addressing? You are even more confused than the person I responded to. The memory would be reclaimed in this scenario, it is entirely “practical” in that sense, there is no contradiction.
Defer /addressing/fixing/solving/ the problem.

If the oomkiller is running, it's too late to wait and see: some process or kernel thread needs memory that the kernel can't currently provide

> If the daemon tries to access that memory, let it crash.

Why not just change Linux's vm.overcommit_memory to not allow overcommitting, so that when a daemon/process does a malloc() an error is returned and it can be handled right away?

I love it! especially if the OS didn't just do this to all recently untouched memory, and did something smart that accurately targeted memory leaks. Like in my case, it's a daemon constantly growing its memory usage at the same rate, and whose heap pages are repetitive and easily compressed. If you could confidently flag the memory as almost certainly a memory leak, I really love it. Honestly it sounds like a thing Apple would do. (and also keep records of the rare case leaked memory is misidentified and accessed later, to improve the process in the future)
I thought about something similiar but more in context of applications like JVM based or go based tools which are loaded in memory and then do not touch certain memroy pages for ages anymore.

Apparently though, tracking pages and access and stuff would be very slow.

I continued thinking about it on how to structure go or jvm apps that you split it in processes so they are more bound to when they are needed and you unload parts of your tool/programm by just handing over the results from one process to the other and kill it.

Or swap it to a less expensive medium, such as the SSD.
That’s actually a very old idea, called paging or swapping. And it totally works
Yes, that is what I am referring to.
Gonna party like it's 1969, I love AI!

Not how I expected the next big optimization push, but I'll take it.

I'd rather not have it waste write cycles

... but reading say libraries directly and only putting in RAM the parts often used, now we're talking

You could page to an HDD too. Or /dev/null
I thought this is what Meta ended up doing, as well as making it very aggressive to push data into compressed memory on servers.
It's like having a room that shrinks everything to 1/5th of its size but you never come back to get anything. It will work until gets full.
I… this is a surprisingly accurate metaphoric abstraction for narcissism. Long story. I mean it though.

Apologies for the off-topicness?

—This is in earnest. The brain does operate according to information theory, certainly has memory, and does compress things.

Nice one
Apple chips have hardware offload for compression that allows for higher compression ratios without paying a substantial latency or power penalty. Android also does this, but with a less optimal compression ratio due to having to do it via CPU instructions.
If the user was feeling stochastic, the OS could theoretically just drop pages that haven't been accessed in, say, 2 days, and send the process a segfault if it tries to access them.

Thus solving memory leaks forever...

I believe one can create a kernel module called leaky_ram to make this possible. No?
No need for a kernel module. Create a FUSE filesystem in user space on which to create a swap file. Once any written block is more than 2 days old just discard it. When they are accessed give EIO. This IIRC translates to a SIGBUS signal in the process.
If you actually do this, make sure no use of that system ever reports a bug on any software they use, ever.
Memory compression is not new to the Mac.

I remember RAM Doubler from 1994 doing this.

https://apple.fandom.com/wiki/RAM_Doubler

The BackRAMs
Wait until people find out about swapping.
Oh we found out about it. In the old days, a machine with a load of 57380 (probably not the highest number I have seen) means the machine has run out of memory and started swapping heavily.

Fun days.

Now, we find out when the SSD wears out, in the worst case.

How long does a wear leveling SSD take to fail if it is set to constantly write at it's fastest possible bandwidth?
>constantly write at it's fastest possible bandwidth?

Not very long especially on modern consumer SSD. Depending on Drive size, at that speed we are talking about full drive write in ~5 to 10 min. On a 5-year warranty SSD that is about 1 - 2 weeks. We have tested Consumer SSD to last beyond their warranty. But even doubling that would only give you 2 - 4 weeks max.

Ouch. Seems like there's a market for something between RAM and Flash in terms of price per bit and dynamic usage.

Volatile memory that was significantly slower than RAM but could be parallelised to wide pipes for wide bandwidth.

Maybe just more flash to allow for more redundancy. Even if flash only lasted a week it's only two or three orders of magnitude to allow for practically usable lifetimes.

A rather amusing idea would be to have a box containing 1024 MicroSDs with a 512 byte block write. Wire them in parallel and you could do a swap drive with 512k blocks with rather impressive bandwidth. Setting them to actively use 0.1% of their data space and wear level across the whole thing they should last a fair few years at full usage. If you were treating them purely as swap you could tune your data size and consider the flash as a consumable. A quick google suggests that RAM is 100x flash, and that micro-SD and SSDs are roughly comparable now at price per bit. Maybe the sweet spot is around 10x redundancy in storage capacity. Then for the price of RAM you could get 10x that in swap with a really big pipe. 10x and cleverness might be ok (reads dominating in real world usage, even for swap, error correction might be able to squeeze quite a lot out with redundancy space.

I look forward to a crazy youtuber making one.

an intel optane card will solve this for you, I'm still waiting to see if I should get one for an slog, but my home lab isn't write heavy enough for this
I mean unless there are some specific needs or bugs, most consumer usage simply dont blown out SSD in their life time. Even in cases with 8GB memory and Safari being still appalling with memory management on many tabs, you are at worst doing 100 - 200GB write per day. On a modern Mac with 16GB base memory, you could be doing 20 - 50GB write per day. Your SSD would easily last 10+ years.
I recently looked at my SSD health with crystal disk info and one of my SATA SSDs is rated for 150TBW and is currently at ~350TBW (with 8% health remaining). It is currentlly at 56k hours power on.
One of my less proud moments was blowing half the life of a new datacenter ssd by forgetting to set limits on the burn in test and assuming it'd be fine like any other drive I ever tested.

Came back the next morning and was happy to find that the tests hadn't failed, unfortunately they had also gone far quicker than I had anticipated and had something silly like 2PB written.

Luckily the other half was more than plenty

Two weeks to six months, depending on the drive design and the rate/size.
That’s odd. Load averages usually aren’t high when swapping; swapping means the CPU isn’t busy.
Try swapping a couple of high performance and multi-core jobs which makes tons of random read & write from RAM to a couple of SATA drives (you can use a good RAID adapter as well), and you'll have nice IOWAIT values pinned to 99%.

Give it some time and you'll see numbers you believe was impossible to display on the output of uptime command. (:

SSD has been retconned to stand for "Storage. Speedy. and… Disposable".

Kidding/not kidding.

I've come to regard SSDs as ephemeral. I stripe-RAID them in my workstation to sum their speed as well as their failure rate. (Which actually also distributes the wear, so…)

And then I use the combined speed and terror to kindle the motivational fire of getting a proper backup solution underneath it.

It depends. I have seen consumer SSDs die in weeks, write oriented SSDs (Specifically designed to be LOG disks of Sun ZFS storage units) run for years under heavy load.

Currently we run some datacenter SSDs which handle constant load just fine, despite being TLCs.

I believe they really put some magic smoke in these chips, because the endurance numbers are just black art at this point. Even my system SSD, which is an EVO860 256GB shows its wear level at 33% after 44K hours.

My /home disk, a 980 Pro 2TB, shows 1% wear after 835 hours. That machine is on 24/7.

In my case, the leaking compressed memory is almost certainly also being swapped to disk. I don't know this for sure, but I can observe that macOS makes very few reads to the swap file. So the swap file is storing memory that is very unlikely to be accessed anyway. It's almost like the other commenter's suggestion to free the leaking memory and crash the program if it tries to access it. But instead of freeing the memory, its puts it into the swap, but with pretty high confidence the memory will never be read.
Paging to disk has also become vastly more transparent, and less of a last resort, with M.2 SSDs. No more things slowing down 10x and endless HD noise when out of RAM.
It's also something that Optane was basically purpose-built to solve, to the point of just shipping on DIMMs directly.

A shame it's dead.

Running out of VRAM and swapping to normal RAM still seems crazy expensive.
Why the downvotes? I also was thinking that's a perfect candidate for swapping to disk.
You can also combine both. Linux has zswap.
Tell me more. I'm on Debian, using mostly ext4 filesystems.
There's Chris Down's Debunking zswap and zram myths (<https://news.ycombinator.com/item?id=47500746>).

If you want to check out whether your system has zswap enabled, you can look at /sys/module/zswap/parameters/enabled, which will be 0 if zswap isn't enabled and 1 or Y if it is. You can look at the kernel docs (<https://docs.kernel.org/admin-guide/mm/zswap.html>) for more.

Terrific, thank you, I will look into this.
> Tell me more.

I tried to summarise hows and whys here, in case it helps:

https://www.theregister.com/on-prem/2026/03/13/ram-is-gettin...

I will go over that, thank you.
Sorry, not familiar with details, I just know it's there.
Zram also became default in Fedora 33.