Deleting ain’t easy

time to read 7 min | 1352 words

We started getting test failures in Voron regarding to being unable to cleanup the data directory. Which was a major cause for concern. We thought that we had a handle leak, or something like that.

As it turned out, we could reproduce this issue with the following code:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         var name = Guid.NewGuid().ToString();
   6:         for (int i = 0; i < 1000; i++)
   7:         {
   8:             Console.WriteLine(i);
   9:             Directory.CreateDirectory(name);
  10:  
  11:             for (int j = 0; j < 10; j++)
  12:             {
  13:                 File.WriteAllText(Path.Combine(name, "test-" +j), "test");
  14:             }
  15:  
  16:             if (Directory.Exists(name))
  17:                 Directory.Delete(name, true);
  18:         }
  19:         
  20:     }
  21: }

If you run this code, in 6 out of 10 runs, it would fail with something like this:

image

I am pretty sure that the underlying cause is some low lever “thang” somewhere on my system. FS Indexing, AV, etc. But it basically means that directory delete is not atomic, and that I should basically just suck it up and write a robust delete routine that can handle failure and retry until it is successful.