back to the school

SageFs.Core/LiveTestWatcherCore.fs

   1  namespace SageFs
   2  
   3  /// Pure single-owner decision core for the live-test file watcher (roast-9
   4  /// #10). This module contains no IO: it only decides, given the current
   5  /// state and an incoming message, what the new state is and which effects
   6  /// the impure shell (LiveTestWatcherManager in SageFs/DaemonMode.fs) must
   7  /// carry out. One MailboxProcessor owns the state and runs the effects, so
   8  /// every message is processed FIFO by a single owner — no lock, no
   9  /// ConcurrentDictionary, no epoch/generation counter.
  10  ///
  11  /// Why the old epoch/stale-event guard (LiveTestWatcherStaleGuard) is gone:
  12  /// with a single-owner mailbox, a FileSaved message posted by a watcher that
  13  /// is later torn down always sits BEHIND the RemoveDirectory/StopWatch
  14  /// message that tore it down (FIFO on one owner). By the time DebounceElapsed
  15  /// drains that path, `sessionsForPath` is evaluated against the CURRENT
  16  /// DirSessions, which no longer has a claim for it — so the stale reload is
  17  /// dropped by construction, not by a race-prone epoch comparison.
  18  ///
  19  /// Top-level module (not nested) so FSI / REPL consumers can resolve
  20  /// `LiveTestWatcherCore.apply` etc. by name.
  21  module LiveTestWatcherCore =
  22  
  23    open WorkerProtocol
  24  
  25    /// Everything that can change watcher state arrives as one of these.
  26    type Msg =
  27      /// A session claims a directory should be watched.
  28      | AddDirectory of dir: string * sessionId: SessionId
  29      /// A session drops its claim on a directory.
  30      | RemoveDirectory of dir: string * sessionId: SessionId
  31      /// Replace all session claims with exactly this (sessionId, dir) list —
  32      /// used on a daemon tick to reconcile watched dirs to the live session set.
  33      | SyncToSessions of sessions: (SessionId * string) list
  34      /// A watched file changed (posted by a FileSystemWatcher callback, already
  35      /// filtered by the shell for watched-extension / not-nested-checkout).
  36      | FileSaved of path: string
  37      /// The debounce window elapsed — drain whatever paths are pending.
  38      | DebounceElapsed
  39  
  40    /// What the shell must actually do as a result of applying a message.
  41    /// StartWatch/StopWatch are directory-level (create/dispose a
  42    /// FileSystemWatcher); ArmDebounce (re)starts the debounce timer;
  43    /// DrainPending hands the shell the coalesced path set to resolve and read.
  44    type Effect =
  45      | StartWatch of dir: string
  46      | StopWatch of dir: string
  47      | ArmDebounce
  48      | DrainPending of paths: string list
  49  
  50    /// DirSessions: dir -> the session IDs that claim it (empty/absent = no
  51    /// claim). Pending: paths saved since the last debounce drain. Watched: the
  52    /// dirs the core currently believes are (or should be) watched — this is
  53    /// recomputed by `reconcile` and always equals `neededDirs fallback DirSessions`
  54    /// after any message is applied.
  55    type State =
  56      { DirSessions: Map<string, SessionId list>
  57        Pending: Set<string>
  58        Watched: Set<string> }
  59  
  60    let empty: State =
  61      { DirSessions = Map.empty
  62        Pending = Set.empty
  63        Watched = Set.empty }
  64  
  65    /// The set of directories that must be watched: the fallback dir (if any)
  66    /// plus every dir with at least one real session claim.
  67    let neededDirs (fallbackDir: string option) (dirSessions: Map<string, SessionId list>) : Set<string> =
  68      let claimed =
  69        dirSessions
  70        |> Map.toSeq
  71        |> Seq.filter (fun (_, claims) -> not (List.isEmpty claims))
  72        |> Seq.map fst
  73        |> Set.ofSeq
  74      match fallbackDir with
  75      | Some f -> Set.add f claimed
  76      | None -> claimed
  77  
  78    /// Recompute Watched from DirSessions and emit Start/Stop effects for the
  79    /// diff against the previous Watched set. Called after every message that
  80    /// can change which dirs are needed.
  81    let reconcile (fallbackDir: string option) (state: State) : State * Effect list =
  82      let needed = neededDirs fallbackDir state.DirSessions
  83      let effects =
  84        [ for d in Set.difference needed state.Watched -> StartWatch d ]
  85        @ [ for d in Set.difference state.Watched needed -> StopWatch d ]
  86      { state with Watched = needed }, effects
  87  
  88    /// The pure decision: (fallbackDir, state, msg) -> (newState, effects).
  89    /// No IO happens here — the shell runs the returned effects.
  90    let apply (fallbackDir: string option) (state: State) (msg: Msg) : State * Effect list =
  91      match msg with
  92      | AddDirectory(dir, sessionId) ->
  93        let existing = Map.tryFind dir state.DirSessions |> Option.defaultValue []
  94        let claims = if List.contains sessionId existing then existing else sessionId :: existing
  95        reconcile fallbackDir { state with DirSessions = Map.add dir claims state.DirSessions }
  96      | RemoveDirectory(dir, sessionId) ->
  97        let existing = Map.tryFind dir state.DirSessions |> Option.defaultValue []
  98        let dirSessions =
  99          match existing |> List.filter (fun s -> s <> sessionId) with
 100          | [] -> Map.remove dir state.DirSessions
 101          | remaining -> Map.add dir remaining state.DirSessions
 102        reconcile fallbackDir { state with DirSessions = dirSessions }
 103      | SyncToSessions sessions ->
 104        let desired = sessions |> List.map snd |> Set.ofList
 105        let added =
 106          sessions
 107          |> List.fold
 108            (fun m (sessionId, dir) ->
 109              let existing = Map.tryFind dir m |> Option.defaultValue []
 110              let claims = if List.contains sessionId existing then existing else sessionId :: existing
 111              Map.add dir claims m)
 112            state.DirSessions
 113        let kept = added |> Map.filter (fun dir _ -> desired.Contains dir)
 114        reconcile fallbackDir { state with DirSessions = kept }
 115      | FileSaved path -> { state with Pending = Set.add path state.Pending }, [ ArmDebounce ]
 116      | DebounceElapsed -> { state with Pending = Set.empty }, [ DrainPending(Set.toList state.Pending) ]
 117  
 118    /// Session ID(s) owning the dir that contains `path` (the deepest containing
 119    /// dir wins; the fallback dir claims no session and is not in DirSessions,
 120    /// so a path under only the fallback dir resolves to []).
 121    /// "Contains" is `PathContainment.isWithin`, the one definition: whole path
 122    /// segments after the platform resolves `.`, `..` and a trailing separator,
 123    /// compared with the platform's case rule. `/a/repo2/x.fs` is not inside
 124    /// `/a/repo`; a text prefix test said it was.
 125    ///
 126    /// Every save in a watched tree asks this. The path is split once and each directory once, and the walk keeps the
 127    /// deepest match as it goes: it used to split the path again for every directory, split each match again to sort by
 128    /// depth, and build a sequence. Two spellings of one directory are the same depth, and the first in the map's order
 129    /// keeps the path (the sort was stable).
 130    let sessionsForPath (dirSessions: Map<string, SessionId list>) (path: string) : SessionId list =
 131      let pathCase = PathContainment.PathCase.ofCurrentOs ()
 132      let pathSegments = PathContainment.fullSegments path
 133      let struct (_, owners) =
 134        dirSessions
 135        |> Map.fold
 136          (fun (struct (deepest, _) as best) dir sessions ->
 137            let rootSegments = PathContainment.fullSegments dir
 138            let depth = List.length rootSegments
 139            match depth > deepest && PathContainment.segmentsWithin pathCase rootSegments pathSegments with
 140            | true -> struct (depth, sessions)
 141            | false -> best)
 142          (struct (-1, []))
 143      owners
 144  
 145    /// Whether `path` is under a directory that is CURRENTLY watched (a claimed
 146    /// session dir OR the session-less fallback dir). The shell uses this, not
 147    /// `sessionsForPath`, to decide whether to fire FileContentChanged on a drain:
 148    /// a file under the fallback dir fires FileContentChanged with no session
 149    /// (the fallback contract), while a save queued before its dir was removed
 150    /// resolves to a dir no longer in `Watched` and is dropped (the stale case).
 151    let isUnderWatchedDir (watched: Set<string>) (path: string) : bool =
 152      let pathCase = PathContainment.PathCase.ofCurrentOs ()
 153      watched |> Set.exists (fun dir -> PathContainment.isWithin pathCase dir path)
 154  
 155  /// What the live-test watcher does with a file that is not F# source: a project file, props, targets, a lock file, the
 156  /// SDK pin, or a data file in the project's folder. The watcher used to see `.fs` and `.fsx` only, so a changed package
 157  /// version or fixture never reached live testing and the status stayed green over a build that no longer matched it.
 158  ///
 159  /// The rule is the landing gate's (`ProjectFileChange.select`, see docs/decisions.md): an edit that only changes a
 160  /// project's compile list runs the tests that cover the files at and after the first difference, and any other change to a
 161  /// build input runs the whole suite. Either way the session is rebuilt first, since only a build reads these files.
 162  module LiveTestBuildInput =
 163  
 164    open SageFs.Features
 165    open SageFs.Features.LiveTesting
 166  
 167    [<RequireQualifiedAccess>]
 168    type BuildInputKind =
 169      /// A `.fsproj`, `.csproj` or `.vbproj`: its text is diffed against the text the watcher saw last.
 170      | ProjectFile
 171      /// Anything else a build reads: props, targets, a lock file, the SDK pin, a resource or data file. Any change to its
 172      /// content can reach any test.
 173      | OtherInput
 174  
 175    /// What a changed file under a watched directory is to live testing.
 176    [<RequireQualifiedAccess>]
 177    type WatchedFile =
 178      /// `.fs` or `.fsx`: the source save path, unchanged.
 179      | Source
 180      | BuildInput of BuildInputKind
 181      /// Nothing to run: an editor's scratch file, a test run's own output, or a file no build reads.
 182      | Ignored of SageFs.FileWatcher.WatchDrop
 183  
 184    /// File names an editor or a test run writes next to real files while saving or failing: vim's `name~`, `.name.swp` and
 185    /// its `4913` write probe, Emacs' `.#name`, `~name` and `name.tmp`, and Verify's `name.received.ext`. A run that wrote
 186    /// a received file and was then woken by it would never stop.
 187    let isScratchName (fileName: string) : bool =
 188      let lower = fileName.ToLowerInvariant()
 189      lower.StartsWith "~"
 190      || lower.StartsWith ".#"
 191      || lower.EndsWith "~"
 192      || lower.EndsWith ".tmp"
 193      || lower.EndsWith ".swp"
 194      || lower.EndsWith ".swo"
 195      || lower.EndsWith ".swx"
 196      || lower = "4913"
 197      || lower.Contains ".received."
 198  
 199    let classify (path: string) : WatchedFile =
 200      let normalized = path.Replace('\\', '/')
 201      let fileName = System.IO.Path.GetFileName normalized
 202      let lower = fileName.ToLowerInvariant()
 203      // The daemon writes its own state under <session>/.SageFs (warmup replay cache, manifests, friction DB).
 204      // Reading that as a build input makes every state write rebuild the session that wrote it, which writes
 205      // state again — a loop that leaves every row Stale/BuildDisagrees and never settles.
 206      match normalized.Split('/') |> Array.exists (fun part -> part = ".SageFs") with
 207      | true -> WatchedFile.Ignored SageFs.FileWatcher.WatchDrop.UnwatchedExtension
 208      | false ->
 209        match isScratchName fileName with
 210        | true -> WatchedFile.Ignored SageFs.FileWatcher.WatchDrop.TemporaryFile
 211        | false ->
 212          match lower.EndsWith ".fs" || lower.EndsWith ".fsx" with
 213          | true -> WatchedFile.Source
 214          | false ->
 215            match CohortLandingPlan.kindByName path with
 216            | CohortLandingPlan.FileByName.ProjectFile -> WatchedFile.BuildInput BuildInputKind.ProjectFile
 217            | CohortLandingPlan.FileByName.BuildInputByName
 218            | CohortLandingPlan.FileByName.CompiledSource -> WatchedFile.BuildInput BuildInputKind.OtherInput
 219            | CohortLandingPlan.FileByName.Inert -> WatchedFile.Ignored SageFs.FileWatcher.WatchDrop.UnwatchedExtension
 220            | CohortLandingPlan.FileByName.Content ->
 221              // A dotfile (.editorconfig, .DS_Store, .gitattributes) is tooling state, not something a test reads.
 222              match fileName.StartsWith "." with
 223              | true -> WatchedFile.Ignored SageFs.FileWatcher.WatchDrop.UnwatchedExtension
 224              | false -> WatchedFile.BuildInput BuildInputKind.OtherInput
 225  
 226    /// Why the live-test watcher drops an event, or `None` when it queues it. Source keeps the `.fs`/`.fsx` filter it
 227    /// always had; a build input passes the same bin/obj and pattern checks with its own extension; a scratch file or a
 228    /// document is dropped by name. `config.Extensions` is ignored: the kind of file decides it.
 229    let dropReason (config: SageFs.FileWatcher.WatchConfig) (path: string) : SageFs.FileWatcher.WatchDrop option =
 230      let watchedAs (extensions: string list) = SageFs.FileWatcher.dropReason { config with Extensions = extensions } path
 231      match classify path with
 232      | WatchedFile.Ignored reason -> Some reason
 233      | WatchedFile.Source -> watchedAs [ ".fs"; ".fsx" ]
 234      | WatchedFile.BuildInput _ -> watchedAs [ System.IO.Path.GetExtension(path).ToLowerInvariant() ]
 235  
 236    /// What a change to a build input asks of live testing.
 237    [<RequireQualifiedAccess>]
 238    type Action =
 239      /// The file states what it stated before (a save with no change, whitespace or a comment in a project file).
 240      | Unchanged
 241      /// Rebuild, then run this selection.
 242      | Run of ProjectFileChange.Selection
 243  
 244    /// The decision for one changed build input. `relativePath` is the file's path under the session's directory, so the
 245    /// compile list resolves the way the landing gate resolves it; `readText` reads a source file by that same kind of path.
 246    /// For a project file `before` and `after` are its texts (`None` for a side that did not exist). For any other input
 247    /// they are fingerprints of its content.
 248    let decide
 249      (readText: string -> string option)
 250      (relativePath: string)
 251      (kind: BuildInputKind)
 252      (before: string option)
 253      (after: string option)
 254      : Action =
 255      match kind with
 256      | BuildInputKind.ProjectFile ->
 257        match ProjectFileChange.diff relativePath before after with
 258        | [] -> Action.Unchanged
 259        | changes -> Action.Run (ProjectFileChange.select readText changes)
 260      | BuildInputKind.OtherInput ->
 261        match before = after with
 262        | true -> Action.Unchanged
 263        | false -> Action.Run (ProjectFileChange.Selection.WholeSuite [ ProjectFileChange.Change.OtherBuildInput relativePath ])
 264  
 265    /// Each test's covered files from the session's coverage, the way the landing gate reads them: `None` for a test whose
 266    /// coverage cannot be trusted (no instrumentation, or a bitmap of another size), so the selection keeps it.
 267    let coveredFilesOf
 268      (blind: string list)
 269      (maps: InstrumentationMap array)
 270      (bitmaps: Map<TestId, CoverageBitmap>)
 271      : TestId -> string list option =
 272      let merged = InstrumentationMap.merge maps
 273      fun testId ->
 274        match merged.Slots.Length with
 275        | 0 -> None
 276        | _ ->
 277          match Map.tryFind testId bitmaps with
 278          | Some bitmap when bitmap.Count = merged.TotalProbes && bitmap.Count > 0 ->
 279            Some (InputHashCoverage.selectionFiles blind merged bitmap)
 280          | _ -> None
 281  
 282    /// The tests a selection runs. A narrow that selects nothing runs the whole suite, the landing gate's floor: a build
 283    /// input changed, and a run of nothing would leave every result standing over a build it no longer describes.
 284    let testsFor
 285      (selection: ProjectFileChange.Selection)
 286      (coveredFilesOf: TestId -> string list option)
 287      (tests: TestCase array)
 288      : TestCase array =
 289      match selection with
 290      | ProjectFileChange.Selection.WholeSuite _ -> tests
 291      | ProjectFileChange.Selection.NarrowToFiles files ->
 292        let chosen =
 293          AffectedTests.affected files coveredFilesOf (tests |> Array.map (fun test -> test.Id) |> Array.toList) |> Set.ofList
 294        match Set.isEmpty chosen with
 295        | true -> tests
 296        | false -> tests |> Array.filter (fun test -> chosen.Contains test.Id)
 297  
 298    /// A build input's content as the watcher compares it: a project file's text, any other input's SHA-256. `None` when
 299    /// the file is gone or cannot be read.
 300    let read (kind: BuildInputKind) (path: string) : string option =
 301      try
 302        match System.IO.File.Exists path, kind with
 303        | false, _ -> None
 304        | true, BuildInputKind.ProjectFile -> Some (System.IO.File.ReadAllText path)
 305        | true, BuildInputKind.OtherInput ->
 306          use stream = System.IO.File.OpenRead path
 307          Some (System.Convert.ToHexString(System.Security.Cryptography.SHA256.HashData stream))
 308      with
 309      | :? System.IO.IOException
 310      | :? System.UnauthorizedAccessException -> None
 311  
 312    /// What each build input under the watched directories said when the watcher last read it, and the decision for the
 313    /// next change against it. The impure edge of `decide`: it reads files. Owned by the watcher's mailbox loop, the
 314    /// only caller, so it takes no lock.
 315    type Store() =
 316      let lastSeen = System.Collections.Generic.Dictionary<string, string>()
 317  
 318      /// Read every project file under `dir` (pruned the way the watcher prunes), so the first edit to one is diffed
 319      /// against the text it had and a compile-list edit narrows from the start. Other inputs are not read ahead: their
 320      /// first change runs the whole suite, which is what any change to them does.
 321      member _.Seed(dir: string) =
 322        for watched in SageFs.FileWatcher.watchableDirs dir SageFs.FileWatcher.hasCheckoutMarker do
 323          try
 324            for file in System.IO.Directory.EnumerateFiles watched do
 325              match classify file with
 326              | WatchedFile.BuildInput BuildInputKind.ProjectFile ->
 327                read BuildInputKind.ProjectFile file |> Option.iter (fun text -> lastSeen[file] <- text)
 328              | WatchedFile.BuildInput BuildInputKind.OtherInput
 329              | WatchedFile.Source
 330              | WatchedFile.Ignored _ -> ()
 331          with
 332          | :? System.IO.IOException
 333          | :? System.UnauthorizedAccessException -> ()
 334  
 335      /// Decide a change to `path`, a build input under one of `watched`, and remember what it says now. The compile list
 336      /// resolves against the deepest watched directory holding the file, the way the landing gate resolves it against
 337      /// the repository root.
 338      member _.Decide(watched: Set<string>, path: string, kind: BuildInputKind) : Action =
 339        let pathCase = PathContainment.PathCase.ofCurrentOs ()
 340        let root =
 341          watched
 342          |> Seq.filter (fun dir -> PathContainment.isWithin pathCase dir path)
 343          |> Seq.fold (fun (best: string) dir -> match dir.Length > best.Length with | true -> dir | false -> best) ""
 344        let relative = System.IO.Path.GetRelativePath(root, path).Replace('\\', '/')
 345        let readText (file: string) =
 346          try Some (System.IO.File.ReadAllText(System.IO.Path.Combine(root, file)))
 347          with
 348          | :? System.IO.IOException
 349          | :? System.UnauthorizedAccessException -> None
 350        let before = match lastSeen.TryGetValue path with | true, seen -> Some seen | false, _ -> None
 351        let after = read kind path
 352        match after with
 353        | Some now -> lastSeen[path] <- now
 354        | None -> lastSeen.Remove path |> ignore
 355        decide readText relative kind before after
 356