After reinstalling Ubuntu on a secondary partition macOS started to boot slower than usual. I tried to check the main APFS volume and encountered some errors. FSCK_APFS was unable to recover this volume (all modes, recovery, single-user). There is no full APFS documentation available in public. No structure explanation. So is it possible to repair APFS manually? Is there any datasheet? What is "fsroot tree" in APFS? Why can it be invalid?

fsck_apfs -y -d /dev/rdisk2s1
Checking volume.
Checking the container superblock.
Checking the EFI jumpstart record.
Checking the space manager.
Checking the object map.
Checking the APFS volume superblock.
Checking the object map.
Checking the fsroot tree.
error: inode_val: object (oid 0xf8aa9): invalid parent_id (0x0)
obj-id: 1010537 type: Inode
private-id: 1010538 parent-id: 0 cr/mtime: 0/0
def-prot-class: -1
uid/gid/mode 0/0/0x81a4 bsd_flags: 0x0 internal_flags: 0x0000 name: NO-NAME
fsroot tree is invalid.
The volume /dev/rdisk2s1 could not be verified completely.

Solution 1:

It might be possible to repair APFS manually, but it requires a lot of insight and experience in working with file systems. If you're not a very technical user (i.e. computer programmer, system administrator, or similar), it's probably going to be out of your reach. The difficulty involved is very much determined by how and how much your file system was damaged.

As far as I know, there's no full documentation on the APFS format from Apple. The best available right now is this blog post:

https://blog.cugu.eu/post/apfs/

Combined with information from this paper:

Decoding the APFS file system (paywall)

Decoding the APFS file system (same paper, but no paywall)

You can use the Kaitai Struct program to parse your file system fragments using the following definition file:

https://github.com/cugu/apfs.ksy/blob/master/apfs.ksy

It might be possible to use the errors messages from that when parsing your file system, to figure out where the errors lie.

You can find an APFS-supporting hex editor here:

http://files.tempel.org/iBored/

I'm not sure exactly to which extent it supports APFS, so YMMV.

Be sure to always take a backup copy of your file system and work on that instead of working on the original drive!