diff --git a/otherlibs/stdune/src/path.ml b/otherlibs/stdune/src/path.ml
index 57c1765f40ba..76c1126bc3e1 100644
--- a/otherlibs/stdune/src/path.ml
+++ b/otherlibs/stdune/src/path.ml
@@ -729,6 +729,7 @@ module Build = struct
   let of_local t = t
   let chmod t ~mode = Unix.chmod (to_string t) mode
   let lstat t = Unix.lstat (to_string t)
+  let unlink t = Fpath.unlink (to_string t)
   let unlink_no_err t = Fpath.unlink_no_err (to_string t)
   let to_dyn s = Dyn.variant "In_build_dir" [ to_dyn s ]
 end
diff --git a/otherlibs/stdune/src/path.mli b/otherlibs/stdune/src/path.mli
index 1bc85f1d3511..2c04162760a3 100644
--- a/otherlibs/stdune/src/path.mli
+++ b/otherlibs/stdune/src/path.mli
@@ -193,6 +193,7 @@ module Build : sig
   val chmod : t -> mode:int -> unit
 
   val lstat : t -> Unix.stats
+  val unlink : t -> unit
   val unlink_no_err : t -> unit
 
   module Table : Hashtbl.S with type key = t
diff --git a/src/dune_engine/build_system.ml b/src/dune_engine/build_system.ml
index f1f276d7ea48..2748e4f6bb1e 100644
--- a/src/dune_engine/build_system.ml
+++ b/src/dune_engine/build_system.ml
@@ -536,8 +536,17 @@ end = struct
           in
           let* () =
             Targets.maybe_async (fun () ->
-              Path.Build.Set.iter targets.files ~f:Path.Build.unlink_no_err;
-              Path.Build.Set.iter targets.dirs ~f:(fun dir -> Path.rm_rf (Path.build dir)))
+              let remove_target_dir dir = Path.rm_rf (Path.build dir) in
+              let remove_target_file path =
+                try Path.Build.unlink path with
+                | Unix.Unix_error (EISDIR, _, _) ->
+                  (* If target changed from a directory to a file, delete
+                     in anyway. *)
+                  remove_target_dir path
+                | _ -> ()
+              in
+              Path.Build.Set.iter targets.files ~f:remove_target_file;
+              Path.Build.Set.iter targets.dirs ~f:remove_target_dir)
           in
           let* produced_targets, dynamic_deps_stages =
             (* Step III. Try to restore artifacts from the shared cache. *)
diff --git a/test/blackbox-tests/test-cases/github6575.t b/test/blackbox-tests/test-cases/github6575.t
index 242801e25214..ac1f69d66c70 100644
--- a/test/blackbox-tests/test-cases/github6575.t
+++ b/test/blackbox-tests/test-cases/github6575.t
@@ -12,13 +12,5 @@ We turn it into a single-file test:
   $ mv sometest.t.bak/run.t sometest.t
   $ rm -r sometest.t.bak
 
-FIXME: Dune should detect the change:
-  $ dune build @sometest
-  Error: _build/default/sometest.t: Is a directory
-  -> required by _build/default/sometest.t
-  -> required by alias sometest
-  [1]
-
-After a clean it works as expected:
-  $ dune clean
+Dune detects the change:
   $ dune build @sometest