That doesn't seem like the bug in this case - we're not changing any partitions in this chunk of code, only writing filesystem metadata into one. The important bit is triggering the sleep a second time between the umount and the kpartx -d to allow kernel buffers/caches time to flush - or else call sync() explicitly after umount, but I hope the kernel wouldn't need more than 2 seconds to sync. The extra round-trip through kpartx just adds another 4-second delay.

It makes sense to put the sleep calls immediately after the method which causes the need for the delay. It makes sense to move the pre-existing sleep call to __enter__ since it's really the kpartx -av call which needs the delay, but the new one would better belong in the MountFileSystem __exit__method rather than the LoadDiskImage one, since it's the call to umount within that method which needs the delay.