From 766fd981d025cad8cd60ecfe52f07ea85cbf02da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:16:25 +0100 Subject: [PATCH 1/9] refactor(cli): extract the edit scenario of the library refresh test The scenario takes the way it runs the CLI as a parameter, so another test can run it with different daemon options. --- .../cli/LibraryModelRefreshIntegrationTest.kt | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt b/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt index dea1dd1a..4324b1aa 100644 --- a/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt +++ b/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt @@ -19,13 +19,25 @@ class LibraryModelRefreshIntegrationTest { @Test fun `external edits of a library model outside the project folder are visible in the same daemon and after a restart`() { + val project = prepareProject() + val daemonHome = tempDir.resolve("daemon-home").createDirectories() + exerciseEdits(project, daemonHome) { args -> + runCommandLine(project, "--daemon-home", daemonHome.pathString, *javaAndMpsHomeArgs(), *args.toTypedArray()) + } + } + + /** Copies the library fixture and moves its library folder out of the project folder. */ + private fun prepareProject(): Path { val project = copyTestProject("project-library", tempDir.resolve("project")) - val shared = Files.move(project.resolve("libs"), tempDir.resolve("shared")) + Files.move(project.resolve("libs"), tempDir.resolve("shared")) val libraries = project.resolve(".mps/libraries.xml") libraries.writeText(libraries.readText().replace("${'$'}PROJECT_DIR${'$'}/libs", "${'$'}PROJECT_DIR${'$'}/../shared")) - val libraryModel = shared.resolve("library/models/values.mps") + return project + } + + private fun exerciseEdits(project: Path, daemonHome: Path, run: (List) -> CliResult) { + val libraryModel = tempDir.resolve("shared/library/models/values.mps") val projectModel = project.resolve("solutions/tests/models/library@tests.mps") - val daemonHome = tempDir.resolve("daemon-home").createDirectories() val program = tempDir.resolve("names.groovy").also { it.writeText(""" project.read { @@ -35,10 +47,8 @@ class LibraryModelRefreshIntegrationTest { } """.trimIndent()) } - fun run(vararg args: String): CliResult = - runCommandLine(project, "--daemon-home", daemonHome.pathString, *javaAndMpsHomeArgs(), *args) fun names(): String { - val result = run("code", "run", program.pathString) + val result = run(listOf("code", "run", program.pathString)) assertEquals(0, result.exitCode, result.output) return result.stdout.trim() } @@ -58,7 +68,7 @@ class LibraryModelRefreshIntegrationTest { rename(libraryModel, "LibraryValue", "LibraryValueEdited") assertEquals("LibraryValueEdited;LibraryPassEdited", names(), "library model edit in the same daemon") - assertEquals(0, run("daemon", "stop").exitCode) + assertEquals(0, run(listOf("daemon", "stop")).exitCode) rename(libraryModel, "LibraryValueEdited", "LibraryValueAfterRestart") assertEquals("LibraryValueAfterRestart;LibraryPassEdited", names(), "edit while the daemon was stopped") } finally { From ece4f466eb0ae88ab135d66eb75bdfd94845d516 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Wed, 18 Nov 2026 13:38:05 +0100 Subject: [PATCH 2/9] refactor(daemon): split policy out of ExternalProjectRefresh ExternalProjectRefresh kept what earlier refreshes saw and decided what changed since then. It now follows `one-kind`: - RefreshBaseline (Value) holds what a refresh saw. - externalChangePolicy.kt (Logic) decides which archives to refresh, which folders to load stored files for, and which runtimes to replace. - ExternalProjectRefresh (Adapter) does the VFS and MPS work. It keeps the baseline of the latest refresh as a private cache (`adapter-cache`). moduleRefresh.kt is split. moduleLocations.kt (Adapter) reads where modules are loaded from, now including the class paths of MPS-managed modules. moduleRefresh.kt (Adapter) keeps the VFS refresh functions. A refresh that throws now keeps the whole previous baseline. Before, it kept whatever parts it had updated before the failure. --- .../mops/daemon/ExternalProjectRefresh.kt | 107 +++++++++--------- .../mops/daemon/RefreshBaseline.kt | 23 ++++ .../mops/daemon/externalChangePolicy.kt | 26 +++++ .../mops/daemon/moduleLocations.kt | 58 ++++++++++ .../mops/daemon/moduleRefresh.kt | 33 +----- .../mops/daemon/ExternalChangePolicyTest.kt | 60 ++++++++++ 6 files changed, 225 insertions(+), 82 deletions(-) create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/RefreshBaseline.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/externalChangePolicy.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleLocations.kt create mode 100644 daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalChangePolicyTest.kt diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt index 728d6c9b..1c974cf1 100644 --- a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt @@ -8,8 +8,6 @@ import jetbrains.mps.classloading.ClassLoaderManager import jetbrains.mps.ide.platform.watching.ReloadManager import jetbrains.mps.project.MPSProject import jetbrains.mps.project.Project -import jetbrains.mps.project.facets.JavaModuleFacet -import jetbrains.mps.project.dependency.GlobalModuleDependenciesManager import jetbrains.mps.util.PathManager import jetbrains.mps.vfs.refresh.DefaultCachingContext import kotlinx.coroutines.runBlocking @@ -18,51 +16,54 @@ import java.nio.file.Files import java.nio.file.Path /** - * Refreshes project files, the folders of source modules, and the archives of packaged modules, and replaces runtimes - * whose Java classpath contents changed between requests. + * Adapter. Refreshes project files, the folders of source modules, and the archives of packaged modules, and replaces + * runtimes whose Java classpath contents changed between requests. + * + * Hides: how to make MPS see the changes that other programs made on disk to a project and the modules it loads. + * + * Keeps a cache (`adapter-cache`): the [RefreshBaseline] of the latest refresh that finished. Each refresh compares with + * it, and `externalChangePolicy.kt` decides what changed; without it, a refresh would refresh every archive, load the + * stored files of every folder, and replace every runtime. Not thread-safe: the request gate runs one refresh at a time. */ internal class ExternalProjectRefresh(private val project: Project) { private val classPathFingerprints = ClassPathFingerprints() - private var outputs = snapshot() - private var archiveStamps: Map? = null - private val foldersWithStoredFilesLoaded = mutableSetOf() + private var baseline = RefreshBaseline(classPaths()) private val mpsHome = Path.of(PathManager.getHomePath()) fun refresh() { val mpsProject = project as MPSProject + val previous = baseline ApplicationManager.getApplication().invokeAndWait { val settings = Path.of(requireNotNull(mpsProject.project.basePath)).resolve(".mps") mpsProject.fileSystem.getFile(settings.toString()).refresh(DefaultCachingContext(true, true)) } // The component store reloads project membership separately from MPS's model/module reload sessions. runBlocking { StoreReloadManager.getInstance(mpsProject.project).reloadChangedStorageFiles() } + lateinit var next: RefreshBaseline ApplicationManager.getApplication().invokeAndWait { - refreshModuleFolders() - refreshModuleArchives() + val loaded = refreshModuleFolders(previous.foldersWithStoredFilesLoaded) + val archiveStamps = refreshModuleArchives(previous.archiveStamps) ReloadManager.getInstance().flush() - val current = snapshot() - val changed = current.filter { (module, files) -> outputs[module] != files }.keys - if (changed.isNotEmpty()) { - project.modelAccess.runWriteAction { - val modules = changed.mapNotNull { it.resolve(project.repository) } - project.getComponent(ClassLoaderManager::class.java).reloadModules(modules) - } - } - outputs = current + val classPaths = replaceChangedRuntimes(previous.classPaths) + next = RefreshBaseline(classPaths, archiveStamps, loaded) } + baseline = next } /** * Refreshes the local folders that modules are loaded from: project modules and the modules of libraries that point * at source folders. The persistent VFS keeps records of these files across daemon restarts, so the first time a * folder is seen, the files the VFS has stored under it are loaded into memory before the refresh; - * docs/test-running-design.md explains why. + * docs/test-running-design.md explains why. Returns the folders whose stored files are loaded, [loaded] included. */ - private fun refreshModuleFolders() { + private fun refreshModuleFolders(loaded: Set): Set { val folders = project.modelAccess.computeReadAction { moduleFolders(project, mpsHome) } .mapNotNull { LocalFileSystem.getInstance().findFileByNioFile(it) } - folders.filter { foldersWithStoredFilesLoaded.add(it.toNioPath()) }.forEach(::loadStoredFiles) - VfsUtil.markDirtyAndRefresh(false, true, true, *folders.toTypedArray()) + .associateBy { it.toNioPath() } + val toLoad = foldersToLoad(loaded, folders.keys.toList()) + toLoad.forEach { loadStoredFiles(folders.getValue(it)) } + VfsUtil.markDirtyAndRefresh(false, true, true, *folders.values.toTypedArray()) + return loaded + toLoad } /** @@ -70,43 +71,43 @@ internal class ExternalProjectRefresh(private val project: Project) { * archive with the deployment descriptor and the archives with the source descriptor and models, usually a * separate `-src.jar`. The persistent VFS keeps archive entries and their cached contents across daemon restarts, * and refreshing the archive file itself does not revalidate them, so a replaced archive keeps serving the old - * models until its archive root is refreshed. The first call refreshes every archive because the VFS may predate - * this daemon; later calls refresh only archives whose size or timestamp on disk changed since the previous call. + * models until its archive root is refreshed. [archivesToRefresh] decides which archives to refresh, comparing with + * the [previous] stamps. Returns the current stamps. */ - private fun refreshModuleArchives() { - val current = project.modelAccess.computeReadAction { moduleArchives(project) }.associateWith(ArchiveStamp::of) - val previous = archiveStamps - val changed = if (previous == null) { - current.keys - } else { - current.filter { (archive, stamp) -> previous[archive] != stamp }.keys - } - changed.forEach(::refreshArchive) - archiveStamps = current + private fun refreshModuleArchives(previous: Map?): Map { + val current = project.modelAccess.computeReadAction { moduleArchives(project) }.associateWith(::archiveStamp) + archivesToRefresh(previous, current).forEach(::refreshArchive) + return current } - /** The size and timestamp of an archive on disk, or `null` for a missing archive. */ - private data class ArchiveStamp(val modified: Long, val size: Long) { - companion object { - fun of(archive: Path): ArchiveStamp? = - if (Files.isRegularFile(archive)) { - ArchiveStamp(Files.getLastModifiedTime(archive).toMillis(), Files.size(archive)) - } else null + /** The size and timestamp of [archive] on disk, or `null` for a missing archive. */ + private fun archiveStamp(archive: Path): ArchiveStamp? = + if (Files.isRegularFile(archive)) { + ArchiveStamp(Files.getLastModifiedTime(archive).toMillis(), Files.size(archive)) + } else null + + /** + * Replaces the runtimes of the modules that [modulesToReload] picks, comparing with the [previous] class paths. + * Returns the current class paths. + */ + private fun replaceChangedRuntimes( + previous: Map>, + ): Map> { + val current = classPaths() + val changed = modulesToReload(previous, current) + if (changed.isNotEmpty()) { + project.modelAccess.runWriteAction { + val modules = changed.mapNotNull { it.resolve(project.repository) } + project.getComponent(ClassLoaderManager::class.java).reloadModules(modules) + } } + return current } - private fun snapshot(): Map>> { - val classPaths = project.modelAccess.computeReadAction { - val modules = GlobalModuleDependenciesManager(project.projectModulesWithGenerators) - .getModules(GlobalModuleDependenciesManager.Deptype.EXECUTE) - modules.mapNotNull { module -> - val facet = module.getFacet(JavaModuleFacet::class.java) - if (facet == null || facet.loadClasses != JavaModuleFacet.LoadClasses.ManagedByMPS) return@mapNotNull null - // A nested archive entry is replaced when its containing archive changes. - module.moduleReference to facet.classPath.map { entry -> Path.of(entry.substringBefore("!/")) } - }.toMap() - } + /** The class path of each module whose classes MPS manages, with a fingerprint of each root. */ + private fun classPaths(): Map> { + val classPaths = project.modelAccess.computeReadAction { managedClassPaths(project) } val fingerprints = classPathFingerprints.compute(classPaths.values.flatten()) - return classPaths.mapValues { (_, roots) -> roots.map { it to fingerprints.getValue(it) } } + return classPaths.mapValues { (_, roots) -> roots.map { ClassPathRoot(it, fingerprints.getValue(it)) } } } } diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/RefreshBaseline.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/RefreshBaseline.kt new file mode 100644 index 00000000..2fa2a874 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/RefreshBaseline.kt @@ -0,0 +1,23 @@ +package com.specificlanguages.mops.daemon + +import org.jetbrains.mps.openapi.module.SModuleReference +import java.nio.file.Path + +/** + * Value. What a refresh saw, for the next refresh to compare with: + * + * - [classPaths]: the Java class path of each module whose classes MPS manages; + * - [archiveStamps]: the stamps of the archives that packaged modules are loaded from, `null` before the first refresh; + * - [foldersWithStoredFilesLoaded]: the module folders whose stored VFS files were loaded into memory. + */ +internal data class RefreshBaseline( + val classPaths: Map>, + val archiveStamps: Map? = null, + val foldersWithStoredFilesLoaded: Set = emptySet(), +) + +/** Value. A class path root and a fingerprint of its contents. */ +internal data class ClassPathRoot(val path: Path, val fingerprint: String) + +/** Value. The size and timestamp of an archive on disk. */ +internal data class ArchiveStamp(val modified: Long, val size: Long) diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/externalChangePolicy.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/externalChangePolicy.kt new file mode 100644 index 00000000..ab0fb67c --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/externalChangePolicy.kt @@ -0,0 +1,26 @@ +/** + * Logic. Hides: which changes since the previous refresh make a refresh refresh a module archive, load the stored files + * of a module folder, or replace a module's runtime. + */ +package com.specificlanguages.mops.daemon + +import org.jetbrains.mps.openapi.module.SModuleReference +import java.nio.file.Path + +/** + * The archives to refresh. The first refresh ([previous] is `null`) refreshes every archive, because the persistent VFS + * may predate this daemon. Later refreshes refresh the archives whose stamp changed. [current] maps a missing archive to + * `null`, so an archive that appears or disappears on disk counts as changed. + */ +internal fun archivesToRefresh(previous: Map?, current: Map): Set = + if (previous == null) current.keys else current.filter { (archive, stamp) -> previous[archive] != stamp }.keys + +/** The module folders in [folders] whose stored files are not in [loaded] yet, in order and without duplicates. */ +internal fun foldersToLoad(loaded: Set, folders: List): List = + folders.distinct().filterNot { it in loaded } + +/** The modules whose runtimes to replace: those whose class path or class path contents changed. */ +internal fun modulesToReload( + previous: Map>, + current: Map>, +): Set = current.filter { (module, roots) -> previous[module] != roots }.keys diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleLocations.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleLocations.kt new file mode 100644 index 00000000..d1a186b7 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleLocations.kt @@ -0,0 +1,58 @@ +/** + * Adapter. Hides: which archives, folders and class path roots on disk the modules in a project's repository are loaded + * from. + */ +package com.specificlanguages.mops.daemon + +import jetbrains.mps.extapi.persistence.FileBasedModelRoot +import jetbrains.mps.project.AbstractModule +import jetbrains.mps.project.Project +import jetbrains.mps.project.dependency.GlobalModuleDependenciesManager +import jetbrains.mps.project.facets.JavaModuleFacet +import jetbrains.mps.vfs.IFile +import org.jetbrains.mps.openapi.module.SModuleReference +import java.nio.file.Path + +/** The archives that the packaged modules in [project]'s repository are loaded from. Requires model read access. */ +internal fun moduleArchives(project: Project): Set = + project.repository.modules.filterIsInstance() + .flatMap { module -> listOfNotNull(module.descriptorFile) + sourceLocations(module) } + .filter { it.isInZipArchive }.map { Path.of(it.path.substringBefore("!/")) }.toSet() + + +/** + * The local folders that the modules in [project]'s repository are loaded from, outside the MPS distribution at + * [mpsHome] and none inside another: the folder of the module descriptor, the module source folder, and the content + * folders of file-based model roots. This covers project modules and the modules of libraries that point at source + * folders. Requires model read access. + */ +internal fun moduleFolders(project: Project, mpsHome: Path): List { + val distribution = setOf(mpsHome.normalize(), mpsHome.toRealPath()) + val folders = project.repository.modules.filterIsInstance() + .flatMap { module -> listOfNotNull(module.descriptorFile?.parent) + sourceLocations(module) } + .filterNot { it.isInZipArchive }.map { Path.of(it.path).normalize() } + .filterNot { folder -> distribution.any(folder::startsWith) }.distinct() + return folders.filter { folder -> folders.none { it != folder && folder.startsWith(it) } } +} + + +/** + * The Java class path roots of each module that [project]'s modules need at run time and whose classes MPS manages. A + * nested archive entry is reported as its containing archive, which is replaced when the entry changes. Requires model + * read access. + */ +internal fun managedClassPaths(project: Project): Map> = + GlobalModuleDependenciesManager(project.projectModulesWithGenerators) + .getModules(GlobalModuleDependenciesManager.Deptype.EXECUTE) + .mapNotNull { module -> + val facet = module.getFacet(JavaModuleFacet::class.java) + if (facet == null || facet.loadClasses != JavaModuleFacet.LoadClasses.ManagedByMPS) return@mapNotNull null + module.moduleReference to facet.classPath.map { entry -> Path.of(entry.substringBefore("!/")) } + }.toMap() + + +/** The module source folder of [module] and the content folders of its file-based model roots. */ +private fun sourceLocations(module: AbstractModule): List = + listOfNotNull(module.moduleSourceDir) + + module.modelRoots.filterIsInstance().mapNotNull { it.contentDirectory } + diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleRefresh.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleRefresh.kt index 5c65c04c..8a650227 100644 --- a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleRefresh.kt +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/moduleRefresh.kt @@ -1,3 +1,7 @@ +/** + * Adapter. Hides: what the VFS keeps about module archives and folders apart from the files themselves (the entries of + * an archive, the files it has stored under a folder), and how to bring that into memory and up to date. + */ package com.specificlanguages.mops.daemon import com.intellij.openapi.vfs.JarFileSystem @@ -7,10 +11,6 @@ import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.openapi.vfs.newvfs.NewVirtualFile -import jetbrains.mps.extapi.persistence.FileBasedModelRoot -import jetbrains.mps.project.AbstractModule -import jetbrains.mps.project.Project -import jetbrains.mps.vfs.IFile import java.nio.file.Path /** @@ -29,31 +29,6 @@ internal fun refreshArchive(archive: Path) { VfsUtil.markDirtyAndRefresh(false, false, false, local) } -/** The archives that the packaged modules in [project]'s repository are loaded from. Requires model read access. */ -internal fun moduleArchives(project: Project): Set = - project.repository.modules.filterIsInstance() - .flatMap { module -> listOfNotNull(module.descriptorFile) + sourceLocations(module) } - .filter { it.isInZipArchive }.map { Path.of(it.path.substringBefore("!/")) }.toSet() - -/** - * The local folders that the modules in [project]'s repository are loaded from, outside the MPS distribution at - * [mpsHome] and none inside another: the folder of the module descriptor, the module source folder, and the content - * folders of file-based model roots. This covers project modules and the modules of libraries that point at source - * folders. Requires model read access. - */ -internal fun moduleFolders(project: Project, mpsHome: Path): List { - val distribution = setOf(mpsHome.normalize(), mpsHome.toRealPath()) - val folders = project.repository.modules.filterIsInstance() - .flatMap { module -> listOfNotNull(module.descriptorFile?.parent) + sourceLocations(module) } - .filterNot { it.isInZipArchive }.map { Path.of(it.path).normalize() } - .filterNot { folder -> distribution.any(folder::startsWith) }.distinct() - return folders.filter { folder -> folders.none { it != folder && folder.startsWith(it) } } -} - -/** The module source folder of [module] and the content folders of its file-based model roots. */ -private fun sourceLocations(module: AbstractModule): List = - listOfNotNull(module.moduleSourceDir) + - module.modelRoots.filterIsInstance().mapNotNull { it.contentDirectory } /** Loads into memory the files the VFS has stored under [folder], without listing folders on disk. */ internal fun loadStoredFiles(folder: VirtualFile) { diff --git a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalChangePolicyTest.kt b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalChangePolicyTest.kt new file mode 100644 index 00000000..96a12a98 --- /dev/null +++ b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalChangePolicyTest.kt @@ -0,0 +1,60 @@ +package com.specificlanguages.mops.daemon + +import jetbrains.mps.project.ModuleId +import jetbrains.mps.project.structure.modules.ModuleReference +import org.jetbrains.mps.openapi.module.SModuleReference +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals + +class ExternalChangePolicyTest { + private val a = Path.of("/libs/a.jar") + private val b = Path.of("/libs/b.jar") + private val c = Path.of("/libs/c.jar") + + @Test + fun `the first refresh refreshes every archive`() { + assertEquals(setOf(a, b), archivesToRefresh(null, mapOf(a to ArchiveStamp(1, 1), b to null))) + } + + @Test + fun `later refreshes refresh archives whose stamp changed`() { + val previous = mapOf(a to ArchiveStamp(1, 1), b to ArchiveStamp(1, 1), c to null) + val current = mapOf( + a to ArchiveStamp(1, 1), + b to ArchiveStamp(2, 1), + c to ArchiveStamp(1, 1), + Path.of("/libs/new.jar") to ArchiveStamp(1, 1), + Path.of("/libs/missing.jar") to null, + ) + assertEquals(setOf(b, c, Path.of("/libs/new.jar")), archivesToRefresh(previous, current)) + } + + @Test + fun `stored files are loaded once per folder`() { + assertEquals(listOf(b, c), foldersToLoad(setOf(a), listOf(a, b, c, b))) + } + + @Test + fun `modules whose class path or its contents changed are reloaded`() { + val unchanged = module("unchanged") + val newFingerprint = module("newFingerprint") + val newRoot = module("newRoot") + val added = module("added") + val previous = mapOf( + unchanged to listOf(ClassPathRoot(a, "1")), + newFingerprint to listOf(ClassPathRoot(a, "1")), + newRoot to listOf(ClassPathRoot(a, "1")), + module("removed") to listOf(ClassPathRoot(a, "1")), + ) + val current = mapOf( + unchanged to listOf(ClassPathRoot(a, "1")), + newFingerprint to listOf(ClassPathRoot(a, "2")), + newRoot to listOf(ClassPathRoot(a, "1"), ClassPathRoot(b, "1")), + added to listOf(ClassPathRoot(a, "1")), + ) + assertEquals(setOf(newFingerprint, newRoot, added), modulesToReload(previous, current)) + } + + private fun module(name: String): SModuleReference = ModuleReference(name, ModuleId.regular()) +} From fb1a272796d73335e1ddfc51faa13a4a830ba235 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:17:21 +0100 Subject: [PATCH 3/9] test(daemon): a reader arriving during a refresh waits for its own refresh The existing gate tests now queue their readers behind running exclusive work, so they still describe batches of readers queued before a refresh. The new test fails until the gate stops admitting readers that arrived during the refresh. --- .../mops/daemon/ProjectRequestGateTest.kt | 77 ++++++++++++------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGateTest.kt b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGateTest.kt index 5564349f..efe469a4 100644 --- a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGateTest.kt +++ b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGateTest.kt @@ -9,50 +9,72 @@ import kotlin.test.* class ProjectRequestGateTest { @Test - fun `read batch shares refresh and exclusive work separates later readers`() { - val refreshing = CountDownLatch(1) - val finishRefresh = CountDownLatch(1) + fun `readers queued before a refresh share it and exclusive work separates later readers`() { + val exclusiveRunning = CountDownLatch(1) + val finishExclusive = CountDownLatch(1) val readers = CountDownLatch(2) val finishReads = CountDownLatch(1) val writing = CountDownLatch(1) val finishWrite = CountDownLatch(1) val refreshes = AtomicInteger() - val gate = ProjectRequestGate { - if (refreshes.incrementAndGet() == 1) { - refreshing.countDown() - finishRefresh.awaitChecked() - } - } - val first = task { gate.run(true) { readers.countDown(); finishReads.awaitChecked() } } + val gate = ProjectRequestGate { refreshes.incrementAndGet() } + val running = task { gate.run(false) { exclusiveRunning.countDown(); finishExclusive.awaitChecked() } } try { - refreshing.awaitChecked() + exclusiveRunning.awaitChecked() + val first = task { gate.run(true) { readers.countDown(); finishReads.awaitChecked() } } + first.awaitQueued() val second = task { gate.run(true) { readers.countDown(); finishReads.awaitChecked() } } second.awaitQueued() val exclusive = task { gate.run(false) { writing.countDown(); finishWrite.awaitChecked() } } exclusive.awaitQueued() val later = task { gate.run(true) { refreshes.get() } } later.awaitQueued() - finishRefresh.countDown() + finishExclusive.countDown() readers.awaitChecked() - assertEquals(1, refreshes.get()) + assertEquals(2, refreshes.get()) assertEquals(1, writing.count) assertFalse(later.future.isDone) finishReads.countDown() writing.awaitChecked() - assertEquals(2, refreshes.get()) + assertEquals(3, refreshes.get()) assertFalse(later.future.isDone) finishWrite.countDown() - assertEquals(3, later.result()) + assertEquals(4, later.result()) + running.result() first.result() second.result() exclusive.result() } finally { - finishRefresh.countDown() + finishExclusive.countDown() finishReads.countDown() finishWrite.countDown() } } + @Test + fun `a reader arriving during a refresh waits for its own refresh`() { + val refreshing = CountDownLatch(1) + val finishRefresh = CountDownLatch(1) + val refreshes = AtomicInteger() + val gate = ProjectRequestGate { + if (refreshes.incrementAndGet() == 1) { + refreshing.countDown() + finishRefresh.awaitChecked() + } + } + val first = task { gate.run(true) { refreshes.get() } } + try { + refreshing.awaitChecked() + val second = task { gate.run(true) { refreshes.get() } } + second.awaitQueued() + finishRefresh.countDown() + assertEquals(1, first.result()) + assertEquals(2, second.result()) + } finally { + finishRefresh.countDown() + } + } + @Test fun `a reader arriving during active reads waits for its own refresh`() { val reading = CountDownLatch(1) @@ -75,31 +97,30 @@ class ProjectRequestGateTest { @Test fun `refresh failure is shared by its batch and releases admission`() { - val refreshing = CountDownLatch(1) - val finishRefresh = CountDownLatch(1) + val exclusiveRunning = CountDownLatch(1) + val finishExclusive = CountDownLatch(1) val refreshes = AtomicInteger() val failure = IllegalStateException("refresh failed") val gate = ProjectRequestGate { - if (refreshes.incrementAndGet() == 1) { - refreshing.countDown() - finishRefresh.awaitChecked() - throw failure - } + if (refreshes.incrementAndGet() == 2) throw failure } - val first = task { runCatching { gate.run(true) { fail("must not run") } }.exceptionOrNull() } + val running = task { gate.run(false) { exclusiveRunning.countDown(); finishExclusive.awaitChecked() } } try { - refreshing.awaitChecked() + exclusiveRunning.awaitChecked() + val first = task { runCatching { gate.run(true) { fail("must not run") } }.exceptionOrNull() } + first.awaitQueued() val second = task { runCatching { gate.run(true) { fail("must not run") } }.exceptionOrNull() } second.awaitQueued() val exclusive = task { gate.run(false) { "recovered" } } exclusive.awaitQueued() - finishRefresh.countDown() + finishExclusive.countDown() + running.result() assertSame(failure, first.result()) assertSame(failure, second.result()) assertEquals("recovered", exclusive.result()) - assertEquals(2, refreshes.get()) + assertEquals(3, refreshes.get()) } finally { - finishRefresh.countDown() + finishExclusive.countDown() } } From 4963388d48da9b33146036e8c48e304c735c6b06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:17:38 +0100 Subject: [PATCH 4/9] fix(daemon): admit only readers queued before a refresh into its batch A reader that arrived while a refresh ran shared that refresh, so it could miss an external change made just before it arrived. --- .../mops/daemon/ProjectRequestGate.kt | 29 +++++++++++++++---- docs/daemon-request-concurrency.md | 7 +++-- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGate.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGate.kt index a9c7d332..a357e484 100644 --- a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGate.kt +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ProjectRequestGate.kt @@ -3,21 +3,33 @@ package com.specificlanguages.mops.daemon import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock -/** FIFO admission outside MPS model actions, excluding refreshes and exclusive work from active readers. */ +/** + * State. FIFO admission outside MPS model actions, excluding refreshes and exclusive work from active readers. Only + * requests queued before a refresh starts are admitted after it, so every request sees the external changes made before + * it arrived. + * + * Hides: which requests share a refresh, and when exclusive work runs. + * + * Request threads wait in one queue, so the queue is State; a Value passed between calls cannot make one thread wait + * for another. Thread-safe: every request thread of the daemon shares one gate. Breaks `one-kind`: the admission rules + * live here, next to the queue, because each decision reads and changes the queue under one lock. + */ internal class ProjectRequestGate(private val refresh: () -> Unit) { private val lock = ReentrantLock() private val changed = lock.newCondition() private val waiting = ArrayDeque() private var active = 0 private var refreshing = false + private var issuedTickets = 0L fun run(parallelRead: Boolean, operation: () -> T): T { - val ticket = Ticket(parallelRead) - lock.withLock { + val ticket = lock.withLock { + val ticket = Ticket(parallelRead, ++issuedTickets) waiting.addLast(ticket) while (!ticket.admitted) { if (active == 0 && !refreshing && waiting.first() === ticket) { refreshing = true + val issuedBeforeRefresh = issuedTickets lock.unlock() val failure = try { refresh() @@ -27,19 +39,21 @@ internal class ProjectRequestGate(private val refresh: () -> Unit) { } finally { lock.lock() } - // Readers queued during refresh share its result. The first exclusive ticket ends the batch. + // Readers queued before the refresh started share its result. The first exclusive ticket and the + // first ticket queued during the refresh end the batch. do { val next = waiting.removeFirst() next.failure = failure next.admitted = true active++ - } while (parallelRead && waiting.firstOrNull()?.parallelRead == true) + } while (parallelRead && waiting.firstOrNull()?.sharesRefresh(issuedBeforeRefresh) == true) refreshing = false changed.signalAll() } else { changed.awaitUninterruptibly() } } + ticket } try { ticket.failure?.let { throw it } @@ -52,7 +66,10 @@ internal class ProjectRequestGate(private val refresh: () -> Unit) { } } - private class Ticket(val parallelRead: Boolean) { + private class Ticket(val parallelRead: Boolean, val sequence: Long) { + /** Whether this ticket joins a batch of readers whose refresh started after [issuedBeforeRefresh] tickets. */ + fun sharesRefresh(issuedBeforeRefresh: Long) = parallelRead && sequence <= issuedBeforeRefresh + var admitted = false var failure: Throwable? = null } diff --git a/docs/daemon-request-concurrency.md b/docs/daemon-request-concurrency.md index 9c6554c5..50f28b75 100644 --- a/docs/daemon-request-concurrency.md +++ b/docs/daemon-request-concurrency.md @@ -4,9 +4,10 @@ The daemon accepts connections concurrently. Authenticated pings return daemon m admission, so a long build, test run, or Code Mode program does not block discovery pings. Domain requests enter a FIFO queue outside MPS model actions. With no active request, the first queued caller refreshes -external changes exclusively. If it is a parallel reader, all consecutive readers queued when that refresh finishes -share the refreshed state and run concurrently. The first exclusive request ends the batch. Requests arriving after -admission wait for another refresh after the active batch finishes. There is no batching delay. +external changes exclusively. If it is a parallel reader, the consecutive readers that were queued when that refresh +started share the refreshed state and run concurrently. The batch ends at the first exclusive request or at the first +request that arrived during the refresh, so every request sees the external changes made before it arrived. Later +requests wait for another refresh after the active batch finishes. There is no batching delay. ```text refresh → [list, get-node, find] → refresh → edit → refresh → [list, find] From 474caecd90738cd14e88334b461bec56f659fe6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:18:28 +0100 Subject: [PATCH 5/9] test(daemon): a refresh sees an external edit made right before it Twenty times in a row, for a project model and for a library model outside the project folder. --- .../ExternalProjectRefreshSemanticsTest.kt | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt diff --git a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt new file mode 100644 index 00000000..3dcf58bc --- /dev/null +++ b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt @@ -0,0 +1,73 @@ +package com.specificlanguages.mops.daemon + +import com.specificlanguages.mops.daemon.core.MpsRead +import com.specificlanguages.mops.protocol.MpsNodeJson +import com.specificlanguages.mops.protocol.NodeTarget +import jetbrains.mps.project.MPSProject +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.readText +import kotlin.io.path.writeText +import kotlin.test.Test +import kotlin.test.assertEquals + +/** A refresh sees an external edit of a model file made immediately before it. */ +class ExternalProjectRefreshSemanticsTest { + + @Test + fun `refresh right after an external edit sees the edit of a project model`() { + SharedMpsEnvironment.withOpenProjectCopy { project, projectPath -> + exerciseEdits(project, projectPath.resolve(STRUCTURE_MODEL_PATH), "JsonFile") { + getNode(NodeTarget.InModel(STRUCTURE_MODEL_NAME, JSON_FILE_NODE_ID)) + } + } + } + + @Test + fun `refresh right after an external edit sees the edit of a library model outside the project folder`() { + lateinit var library: Path + SharedMpsEnvironment.withOpenProjectCopy(LIBRARY_PROJECT, prepare = { project -> + library = Files.move(project.resolve("libs"), project.resolveSibling("shared")) + val libraries = project.resolve(".mps/libraries.xml") + libraries.writeText(libraries.readText().replace("${'$'}PROJECT_DIR${'$'}/libs", "${'$'}PROJECT_DIR${'$'}/../shared")) + }) { project, _ -> + exerciseEdits(project, library.resolve("library/models/values.mps"), "LibraryValue") { + getNode(NodeTarget.InModel(LIBRARY_MODEL_NAME, LIBRARY_ROOT_NODE_ID)) + } + } + } + + private fun exerciseEdits( + project: MPSProject, + model: Path, + originalName: String, + node: MpsRead.() -> MpsNodeJson, + ) { + val access = SharedMpsEnvironment.mpsAccess(project) + val refresh = ExternalProjectRefresh(project) + refresh.refresh() + var previousName = originalName + repeat(EDITS) { index -> + val name = "$originalName$index" + model.writeText(model.readText().replace("value=\"$previousName\"", "value=\"$name\"")) + previousName = name + + refresh.refresh() + + assertEquals(name, propertyValue(access.read(node), "name"), "edit $index is visible after the refresh") + } + } + + private companion object { + const val EDITS = 20 + + const val STRUCTURE_MODEL_NAME = "com.specificlanguages.json.structure" + const val STRUCTURE_MODEL_PATH = + "languages/com.specificlanguages.json/models/com.specificlanguages.json.structure.mps" + const val JSON_FILE_NODE_ID = "2110045694544566904" + + const val LIBRARY_PROJECT = "project-library" + const val LIBRARY_MODEL_NAME = "mops.library.values" + const val LIBRARY_ROOT_NODE_ID = "4096" + } +} From e569b3af2000b233cc0b816092b711a7a82dbaeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:19:53 +0100 Subject: [PATCH 6/9] feat(daemon): run the native file watcher in the daemon The daemon plugin registers a native file watcher that also runs in a headless application. Before MPS starts, the daemon copies fsnotifier from the MPS distribution into its workspace and makes it executable, because the generic distribution archive drops the executable bit. Without a binary for the platform it turns the watcher off. Refreshes still walk every folder. --- daemon-mps-plugin/build.gradle.kts | 7 ++ .../plugin/HeadlessNativeFileWatcher.kt | 95 +++++++++++++++++++ .../src/main/resources/META-INF/plugin.xml | 4 + .../mops/daemon/MopsDaemonCommand.kt | 2 + .../filewatcher/FileWatcherExecutable.kt | 69 ++++++++++++++ .../mops/daemon/SharedMpsEnvironment.kt | 6 ++ .../mops/protocol/DaemonRecordStore.kt | 3 + skills/mops-daemon/SKILL.md | 1 + 8 files changed, 187 insertions(+) create mode 100644 daemon-mps-plugin/src/main/kotlin/com/specificlanguages/mops/daemon/plugin/HeadlessNativeFileWatcher.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherExecutable.kt diff --git a/daemon-mps-plugin/build.gradle.kts b/daemon-mps-plugin/build.gradle.kts index 9185c202..65708aac 100644 --- a/daemon-mps-plugin/build.gradle.kts +++ b/daemon-mps-plugin/build.gradle.kts @@ -18,6 +18,13 @@ dependencies { include("lib/mps-openapi.jar") include("lib/mps-persistence.jar") include("lib/util.jar") + // NativeFileWatcherImpl, PluggableFileWatcher, Notifications and their supertypes, for + // HeadlessNativeFileWatcher. + include("lib/util-8.jar") + include("lib/app.jar") + include("lib/intellij.platform.core.jar") + include("lib/intellij.platform.ide.core.jar") + include("lib/intellij.platform.ide.impl.jar") include("plugins/mps-java/lib/java-core.jar") include("plugins/java/lib/ecj/eclipse.jar") } diff --git a/daemon-mps-plugin/src/main/kotlin/com/specificlanguages/mops/daemon/plugin/HeadlessNativeFileWatcher.kt b/daemon-mps-plugin/src/main/kotlin/com/specificlanguages/mops/daemon/plugin/HeadlessNativeFileWatcher.kt new file mode 100644 index 00000000..1fab9f68 --- /dev/null +++ b/daemon-mps-plugin/src/main/kotlin/com/specificlanguages/mops/daemon/plugin/HeadlessNativeFileWatcher.kt @@ -0,0 +1,95 @@ +package com.specificlanguages.mops.daemon.plugin + +import com.intellij.notification.Notification +import com.intellij.notification.Notifications +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.vfs.impl.local.NativeFileWatcherImpl +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong + +/** + * Adapter. The platform's native file watcher (`fsnotifier`), enabled in a headless application. The platform registers + * its own instance, which stays off in command-line and test applications; this second registration differs only in + * that check, and can still be turned off with `-Didea.filewatcher.disabled=true`. + * + * Hides: how the platform's native file watcher behaves in a headless application, including when it may have missed + * changes. + * + * Breaks `connascence-in-types`: the daemon calls [changeCount] and [recursiveRoots] by name, because the plugin class + * loader loads this class and the daemon cannot share a type with it. For the same reason, it names the platform's + * `idea.filewatcher.disabled` property itself, as `FileWatcherExecutable` in the daemon does. + * + * Breaks `adapter-cache`: it keeps the watch roots it was given and whether the watcher reported a failure, which are + * not a cache. The platform tells it about them only by calling [setWatchRoots] and by posting notifications, so + * [changeCount] and [recursiveRoots] are computed from what it kept. + * + * Thread-safe: the platform sets the roots and posts notifications on its own threads while request threads read + * [changeCount] and [recursiveRoots]. + */ +class HeadlessNativeFileWatcher : NativeFileWatcherImpl() { + private val rootChanges = AtomicLong() + + @Volatile + private var recursive: List = emptyList() + + @Volatile + private var flat: List = emptyList() + + @Volatile + private var failed = false + + private val startAttempts: AtomicInteger? = startAttemptCounter() + + init { + ApplicationManager.getApplication().messageBus.connect().subscribe( + Notifications.TOPIC, + object : Notifications { + override fun notify(notification: Notification) { + if (notification.groupId == FAILURE_GROUP) failed = true + } + }, + ) + } + + override fun isDisabled(): Boolean = java.lang.Boolean.getBoolean(DISABLED_PROPERTY) + + override fun setWatchRoots(recursive: List, flat: List, shuttingDown: Boolean) { + if (recursive != this.recursive || flat != this.flat) { + this.recursive = recursive + this.flat = flat + rootChanges.incrementAndGet() + } + super.setWatchRoots(recursive, flat, shuttingDown) + } + + /** + * A number that changes whenever the watcher may have missed changes: when the watch roots change and when the + * `fsnotifier` process is started again. `null` once the watcher has reported a failure, such as the Linux inotify + * watch limit, or when the start count cannot be read. + */ + fun changeCount(): Long? { + val starts = startAttempts ?: return null + return if (failed) null else rootChanges.get() + starts.get() + } + + /** The recursive watch roots as last set, canonical and system-dependent. */ + fun recursiveRoots(): List = recursive + + /** + * The platform restarts a terminated `fsnotifier` without reporting anything as changed, but counts each start in a + * private field. + */ + private fun startAttemptCounter(): AtomicInteger? = + try { + NativeFileWatcherImpl::class.java.getDeclaredField("myStartAttemptCount") + .apply { isAccessible = true } + .get(this) as? AtomicInteger + } catch (_: ReflectiveOperationException) { + null + } + + private companion object { + const val DISABLED_PROPERTY = "idea.filewatcher.disabled" + const val FAILURE_GROUP = "File Watcher Messages" + } +} diff --git a/daemon-mps-plugin/src/main/resources/META-INF/plugin.xml b/daemon-mps-plugin/src/main/resources/META-INF/plugin.xml index cd0ff020..032bf68b 100644 --- a/daemon-mps-plugin/src/main/resources/META-INF/plugin.xml +++ b/daemon-mps-plugin/src/main/resources/META-INF/plugin.xml @@ -9,4 +9,8 @@ + + + diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/MopsDaemonCommand.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/MopsDaemonCommand.kt index 92a7b022..57d88fe8 100644 --- a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/MopsDaemonCommand.kt +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/MopsDaemonCommand.kt @@ -1,5 +1,6 @@ package com.specificlanguages.mops.daemon +import com.specificlanguages.mops.daemon.filewatcher.FileWatcherExecutable import com.specificlanguages.mops.launcher.MpsBuildProperties import com.specificlanguages.mops.protocol.* import de.itemis.mps.gradle.project.loader.EnvironmentKind @@ -68,6 +69,7 @@ class MopsDaemonCommand : Runnable { val workspacePath = Path.of(workspacePath) val mpsPlugin = Path.of(mpsPlugin) + FileWatcherExecutable.install(mpsHome, DaemonWorkspace(workspacePath).fileWatcherDir, logger) DaemonRunner( projectPath = projectPath, diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherExecutable.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherExecutable.kt new file mode 100644 index 00000000..7c4ef03f --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherExecutable.kt @@ -0,0 +1,69 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import com.specificlanguages.mops.daemon.DaemonLogger +import java.io.IOException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import kotlin.io.path.createDirectories +import kotlin.io.path.isRegularFile + +/** + * Adapter. Prepares the native file watcher's executable (`fsnotifier`) before MPS starts. The generic MPS distribution + * archive does not keep the executable bit, so the distribution's binary is copied into a directory of the daemon, made + * executable, and passed to the platform through `idea.filewatcher.executable.path`. Without a binary for this + * platform the watcher is turned off through `idea.filewatcher.disabled`, and refreshes walk folders instead. + * + * Hides: where the MPS distribution keeps `fsnotifier` for each platform, and how the platform is told which one to run. + * + * Does nothing when either property is already set, so `-Didea.filewatcher.disabled=true` in the daemon's Java options + * turns the watcher off. + */ +internal object FileWatcherExecutable { + private const val EXECUTABLE_PROPERTY = "idea.filewatcher.executable.path" + private const val DISABLED_PROPERTY = "idea.filewatcher.disabled" + + fun install(mpsHome: Path, directory: Path, logger: DaemonLogger) { + if (System.getProperty(EXECUTABLE_PROPERTY) != null || System.getProperty(DISABLED_PROPERTY) != null) return + val bundled = bundled(mpsHome) + if (bundled == null) { + logger.log("no native file watcher in $mpsHome for this platform; refreshes walk folders") + System.setProperty(DISABLED_PROPERTY, "true") + return + } + try { + System.setProperty(EXECUTABLE_PROPERTY, copy(bundled, directory).toString()) + } catch (exception: IOException) { + logger.log("cannot prepare the native file watcher $bundled: $exception; refreshes walk folders") + System.setProperty(DISABLED_PROPERTY, "true") + } + } + + private fun copy(bundled: Path, directory: Path): Path { + val target = directory.createDirectories().resolve(bundled.fileName) + if (!target.isRegularFile() || Files.mismatch(bundled, target) != -1L) { + val temporary = Files.createTempFile(directory, bundled.fileName.toString(), ".tmp") + Files.copy(bundled, temporary, StandardCopyOption.REPLACE_EXISTING) + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + if (!Files.isExecutable(target) && !target.toFile().setExecutable(true)) { + throw IOException("cannot make $target executable") + } + return target + } + + /** The distribution's `fsnotifier` for the current operating system and architecture, if it has one. */ + private fun bundled(mpsHome: Path): Path? { + val os = System.getProperty("os.name") + val arm = System.getProperty("os.arch") in setOf("aarch64", "arm64") + val relative = when { + os.startsWith("Mac") -> "bin/mac/fsnotifier" + os.startsWith("Windows") -> "bin/win/fsnotifier.exe" + // Before MPS 2026.3 the distribution has only an x86-64 binary for Linux. + os.startsWith("Linux") && arm -> "bin/linux-aarch64/fsnotifier" + os.startsWith("Linux") -> "bin/linux/fsnotifier" + else -> return null + } + return mpsHome.resolve(relative).takeIf { it.isRegularFile() } + } +} diff --git a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/SharedMpsEnvironment.kt b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/SharedMpsEnvironment.kt index 84212d6a..f48873be 100644 --- a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/SharedMpsEnvironment.kt +++ b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/SharedMpsEnvironment.kt @@ -2,6 +2,7 @@ package com.specificlanguages.mops.daemon import com.intellij.ide.GeneralSettings import com.specificlanguages.mops.daemon.core.MpsAccess +import com.specificlanguages.mops.daemon.filewatcher.FileWatcherExecutable import com.specificlanguages.mops.launcher.MpsLaunchArgs import de.itemis.mps.gradle.project.loader.EnvironmentKind import de.itemis.mps.gradle.project.loader.Plugin @@ -141,6 +142,11 @@ object SharedMpsEnvironment { private fun boot(): IdeaEnvironment { applyMpsSystemProperties() + FileWatcherExecutable.install( + requiredPathProperty("test.mpsHome"), + Files.createTempDirectory("mops-fsnotifier"), + DaemonLogger(), + ) val handoff = SynchronousQueue() val environmentThread = Thread({ diff --git a/protocol/src/main/kotlin/com/specificlanguages/mops/protocol/DaemonRecordStore.kt b/protocol/src/main/kotlin/com/specificlanguages/mops/protocol/DaemonRecordStore.kt index 9db033df..e00f5b87 100644 --- a/protocol/src/main/kotlin/com/specificlanguages/mops/protocol/DaemonRecordStore.kt +++ b/protocol/src/main/kotlin/com/specificlanguages/mops/protocol/DaemonRecordStore.kt @@ -139,6 +139,9 @@ class DaemonWorkspace(val path: Path) { /** The IntelliJ system directory (VFS, indexes, caches) that the test worker keeps between test runs. */ fun testWorkerSystemDir(): Path = path.resolve("test-worker-system") + /** The directory with the native file watcher executable that the daemon copies from the MPS distribution. */ + val fileWatcherDir: Path = path.resolve("fsnotifier") + fun createDirectories() { daemonWorkingDir().createDirectories() ideaConfigDir().createDirectories() diff --git a/skills/mops-daemon/SKILL.md b/skills/mops-daemon/SKILL.md index 9ed211fd..f94283fe 100644 --- a/skills/mops-daemon/SKILL.md +++ b/skills/mops-daemon/SKILL.md @@ -85,6 +85,7 @@ holds: home, workspace path, and startup time. - `logs/daemon.log`: the daemon's startup and runtime log. - `daemon/config` and `daemon/system`: the isolated IDEA directories passed to the daemon JVM. +- `fsnotifier/`: the native file watcher executable, copied from the MPS distribution. - `test-worker-system`: the IntelliJ system directory of the test worker. Only one daemon runs per project. When a command needs a daemon for another MPS home or build than the running one, mops From f696e35b024d5970c5368a871dea4ca921b5a57f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:20:27 +0100 Subject: [PATCH 7/9] test(cli): the daemon log names how each refresh went With the native file watcher available, refreshes use its events. With the watcher turned off through the daemon's Java options, edits stay visible and every refresh walks the folders. Both tests fail until refreshes log their mode. --- .../cli/LibraryModelRefreshIntegrationTest.kt | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt b/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt index 4324b1aa..cefc65bf 100644 --- a/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt +++ b/cli/src/integrationTest/kotlin/com/specificlanguages/mops/cli/LibraryModelRefreshIntegrationTest.kt @@ -1,17 +1,25 @@ package com.specificlanguages.mops.cli +import com.specificlanguages.mops.protocol.DaemonPaths +import com.specificlanguages.mops.protocol.DaemonWorkspace +import org.junit.jupiter.api.Tag import org.junit.jupiter.api.io.CleanupMode import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.api.parallel.ResourceLock import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.createDirectories +import kotlin.io.path.isRegularFile +import kotlin.io.path.listDirectoryEntries import kotlin.io.path.pathString import kotlin.io.path.readText import kotlin.io.path.writeText import kotlin.test.Test +import kotlin.test.assertContains import kotlin.test.assertEquals +import kotlin.test.assertFalse +@Tag("smoke") @ResourceLock("system-streams") class LibraryModelRefreshIntegrationTest { @TempDir(cleanup = CleanupMode.ON_SUCCESS) @@ -24,6 +32,23 @@ class LibraryModelRefreshIntegrationTest { exerciseEdits(project, daemonHome) { args -> runCommandLine(project, "--daemon-home", daemonHome.pathString, *javaAndMpsHomeArgs(), *args.toTypedArray()) } + if (watcherExpected) { + assertContains(daemonLogs(daemonHome), "refreshed external changes using file watcher events") + } + } + + @Test + fun `external edits are visible with the native file watcher turned off`() { + val project = prepareProject() + val daemonHome = tempDir.resolve("daemon-home").createDirectories() + val cli = InstalledCli( + project, daemonHome, tempDir, + mapOf("MOPS_DAEMON_JAVA_OPTIONS" to "-Didea.filewatcher.disabled=true"), + ) + exerciseEdits(project, daemonHome) { args -> cli.run(*args.toTypedArray()) } + val logs = daemonLogs(daemonHome) + assertContains(logs, "using a full walk because the file watcher is not operational") + assertFalse("using file watcher events" in logs, logs) } /** Copies the library fixture and moves its library folder out of the project folder. */ @@ -75,4 +100,15 @@ class LibraryModelRefreshIntegrationTest { stopDaemons(project, daemonHome) } } + + private fun daemonLogs(daemonHome: Path): String = + DaemonPaths(daemonHome).projects.listDirectoryEntries() + .map { DaemonWorkspace(it).logFile() }.filter { it.isRegularFile() }.joinToString("\n") { it.readText() } + + private companion object { + // Every supported MPS version ships fsnotifier for macOS and for Linux on x86-64. + val watcherExpected = System.getProperty("os.name").let { os -> + os.startsWith("Mac") || os.startsWith("Linux") && System.getProperty("os.arch") in setOf("amd64", "x86_64") + } + } } From 5a5491881a2736c970aa7d1786b88f01dee2017e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:24:28 +0100 Subject: [PATCH 8/9] feat(daemon): decide when a refresh can rely on the native file watcher Logic and Values only; nothing calls them yet. assessFileWatcher decides from the watcher's signals whether a refresh can rely on its events, and planFolderRefresh splits the folders into those to walk and those to refresh from events. --- .../daemon/filewatcher/FolderRefreshPlan.kt | 6 ++ .../daemon/filewatcher/FolderRefreshReport.kt | 29 ++++++ .../mops/daemon/filewatcher/FullWalkReason.kt | 13 +++ .../mops/daemon/filewatcher/WatchCoverage.kt | 17 ++++ .../daemon/filewatcher/WatcherAssessment.kt | 13 +++ .../daemon/filewatcher/folderRefreshPolicy.kt | 83 ++++++++++++++++ .../filewatcher/FolderRefreshPolicyTest.kt | 97 +++++++++++++++++++ 7 files changed, 258 insertions(+) create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPlan.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshReport.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FullWalkReason.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatchCoverage.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatcherAssessment.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshPolicy.kt create mode 100644 daemon/src/test/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPolicyTest.kt diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPlan.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPlan.kt new file mode 100644 index 00000000..9170a0c0 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPlan.kt @@ -0,0 +1,6 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import java.nio.file.Path + +/** Value. The folders one refresh walks, and the folders it refreshes from the native file watcher's events. */ +internal data class FolderRefreshPlan(val walk: List, val fromEvents: List) diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshReport.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshReport.kt new file mode 100644 index 00000000..776fa6ad --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshReport.kt @@ -0,0 +1,29 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import java.time.Duration + +/** + * Value. How one refresh refreshed folders and what it cost. [fullWalkReason] is `null` when the refresh relied on the + * native file watcher. + */ +internal data class FolderRefreshReport( + val fullWalkReason: FullWalkReason?, + val watcherWait: Duration, + val fromEvents: Int = 0, + val walked: Int = 0, + val refreshTime: Duration = Duration.ZERO, +) { + /** Adds the folders of [plan], refreshed in [time]. */ + fun withFolders(plan: FolderRefreshPlan, time: Duration): FolderRefreshReport = copy( + fromEvents = fromEvents + plan.fromEvents.size, + walked = walked + plan.walk.size, + refreshTime = refreshTime + time, + ) + + /** The daemon log line of this refresh. */ + fun logLine(): String { + val mode = fullWalkReason?.let { "a full walk because ${it.description}" } ?: "file watcher events" + return "refreshed external changes using $mode: $fromEvents folders from watcher events, $walked walked; " + + "watcher wait ${watcherWait.toMillis()} ms, refresh ${refreshTime.toMillis()} ms" + } +} diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FullWalkReason.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FullWalkReason.kt new file mode 100644 index 00000000..dc7a713f --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FullWalkReason.kt @@ -0,0 +1,13 @@ +package com.specificlanguages.mops.daemon.filewatcher + +/** Why a refresh walks every folder instead of relying on the native file watcher's events. */ +internal enum class FullWalkReason(val description: String) { + NOT_REGISTERED("the mops file watcher is not registered"), + NOT_OPERATIONAL("the file watcher is not operational"), + ROOTS_NOT_SETTLED("the file watcher is still setting its roots"), + FAILURE_REPORTED("the file watcher reported a failure or its restarts cannot be counted"), + NO_EVENT_HOOK("the file watcher event hook is not available"), + FENCE_NOT_REPORTED("the file watcher did not report the fence in time"), + FIRST_REFRESH("this is the first refresh"), + ROOTS_CHANGED("the watch roots changed or the file watcher restarted"), +} diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatchCoverage.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatchCoverage.kt new file mode 100644 index 00000000..ef767429 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatchCoverage.kt @@ -0,0 +1,17 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import java.nio.file.Path + +/** + * Value. Where the native file watcher reports changes in order with the fence at [fenceRoot]. [recursiveRoots] and + * [fenceRoot] are real paths. Without [orderedAcrossDrives], only changes on the fence's drive are in order with it. + */ +internal data class WatchCoverage( + val recursiveRoots: List, + val fenceRoot: Path, + val orderedAcrossDrives: Boolean, +) { + /** Whether a change under [realPath] is reported before the fence that follows it. */ + fun covers(realPath: Path): Boolean = + (orderedAcrossDrives || realPath.root == fenceRoot.root) && recursiveRoots.any(realPath::startsWith) +} diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatcherAssessment.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatcherAssessment.kt new file mode 100644 index 00000000..90c29dcd --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/WatcherAssessment.kt @@ -0,0 +1,13 @@ +package com.specificlanguages.mops.daemon.filewatcher + +/** Whether one refresh can rely on the native file watcher's events. */ +internal sealed interface WatcherAssessment { + /** The watcher's change count, which the next refresh compares with its own. */ + val changeCount: Long? + + /** The watcher has reported every change since the previous refresh under [coverage]. */ + data class Trusted(override val changeCount: Long, val coverage: WatchCoverage) : WatcherAssessment + + /** Every folder is walked, for [reason]. */ + data class FullWalk(val reason: FullWalkReason, override val changeCount: Long?) : WatcherAssessment +} diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshPolicy.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshPolicy.kt new file mode 100644 index 00000000..e9491d13 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshPolicy.kt @@ -0,0 +1,83 @@ +/** + * Logic. Hides: when a folder refresh can rely on the native file watcher's events instead of walking the folder. + * + * A forced refresh (a full walk) visits every file the VFS has loaded under a folder. With the watcher, a fence first + * makes sure the watcher has reported every change made before the request, and a non-forced recursive refresh then + * visits only the files the watcher reported. [FullWalkReason] lists when every folder is walked instead. A folder is + * also walked the first time it is refreshed and whenever the watcher does not cover it ([WatchCoverage]). + */ +package com.specificlanguages.mops.daemon.filewatcher + +import java.nio.file.Path + +/** Logic. What [assessFileWatcher] asks the native file watcher. */ +internal interface FileWatcherSignals { + /** Whether `fsnotifier` runs. */ + fun isOperational(): Boolean + + /** Waits until the watcher has set its watch roots. Returns `false` when it is still setting them after a timeout. */ + fun awaitSettledRoots(): Boolean + + /** Waits until the watcher has reported every change made before this call. */ + fun awaitFence(): Fence + + /** + * A number that changes whenever the watcher may have missed changes, or `null` after it reported a failure or when + * its restarts cannot be counted. + */ + fun changeCount(): Long? + + /** How [awaitFence] ended. */ + sealed interface Fence { + /** The watcher reported the fence, and it reports changes in order with the fence under [coverage]. */ + data class Reported(val coverage: WatchCoverage) : Fence + + /** The watcher did not report the fence in time. */ + data object NotReported : Fence + + /** The watcher's event hook is not available, so there is no fence. */ + data object Unavailable : Fence + } +} + +/** + * Decides whether this refresh can rely on [watcher], which is `null` when the mops file watcher is not registered. + * [previousChangeCount] is the [WatcherAssessment.changeCount] of the previous refresh. + */ +internal fun assessFileWatcher(watcher: FileWatcherSignals?, previousChangeCount: Long?): WatcherAssessment { + if (watcher == null) return WatcherAssessment.FullWalk(FullWalkReason.NOT_REGISTERED, previousChangeCount) + if (!watcher.isOperational()) return WatcherAssessment.FullWalk(FullWalkReason.NOT_OPERATIONAL, previousChangeCount) + if (!watcher.awaitSettledRoots()) { + return WatcherAssessment.FullWalk(FullWalkReason.ROOTS_NOT_SETTLED, previousChangeCount) + } + val fence = watcher.awaitFence() + val changeCount = watcher.changeCount() ?: return WatcherAssessment.FullWalk(FullWalkReason.FAILURE_REPORTED, null) + val reason = when (fence) { + FileWatcherSignals.Fence.Unavailable -> FullWalkReason.NO_EVENT_HOOK + FileWatcherSignals.Fence.NotReported -> FullWalkReason.FENCE_NOT_REPORTED + is FileWatcherSignals.Fence.Reported -> when (previousChangeCount) { + null -> FullWalkReason.FIRST_REFRESH + changeCount -> return WatcherAssessment.Trusted(changeCount, fence.coverage) + else -> FullWalkReason.ROOTS_CHANGED + } + } + return WatcherAssessment.FullWalk(reason, changeCount) +} + +/** + * Splits [folders] into the folders to walk and the folders to refresh from watcher events. A folder is refreshed from + * events only when [assessment] trusts the watcher, the folder is in [refreshedBefore], and the watcher covers its + * [realPath], which is `null` for a folder that cannot be resolved. + */ +internal fun planFolderRefresh( + folders: List, + assessment: WatcherAssessment, + refreshedBefore: Set, + realPath: (Path) -> Path?, +): FolderRefreshPlan { + val coverage = (assessment as? WatcherAssessment.Trusted)?.coverage + val (fromEvents, walk) = folders.partition { folder -> + coverage != null && folder in refreshedBefore && realPath(folder)?.let(coverage::covers) == true + } + return FolderRefreshPlan(walk = walk, fromEvents = fromEvents) +} diff --git a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPolicyTest.kt b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPolicyTest.kt new file mode 100644 index 00000000..e23f61b5 --- /dev/null +++ b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefreshPolicyTest.kt @@ -0,0 +1,97 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import com.specificlanguages.mops.daemon.filewatcher.FileWatcherSignals.Fence +import java.nio.file.Path +import java.time.Duration +import kotlin.test.Test +import kotlin.test.assertEquals + +class FolderRefreshPolicyTest { + @Test + fun `a watcher that reported the fence with an unchanged count is trusted`() { + assertEquals(WatcherAssessment.Trusted(7, coverage), assessFileWatcher(FakeSignals(), previousChangeCount = 7)) + } + + @Test + fun `each failed check walks every folder and keeps the change count it read`() { + val cases = listOf( + Triple(null, 7L, WatcherAssessment.FullWalk(FullWalkReason.NOT_REGISTERED, 7)), + Triple(FakeSignals(operational = false), 7L, WatcherAssessment.FullWalk(FullWalkReason.NOT_OPERATIONAL, 7)), + Triple(FakeSignals(settled = false), 7L, WatcherAssessment.FullWalk(FullWalkReason.ROOTS_NOT_SETTLED, 7)), + Triple(FakeSignals(changeCount = null), 7L, WatcherAssessment.FullWalk(FullWalkReason.FAILURE_REPORTED, null)), + Triple(FakeSignals(fence = Fence.Unavailable), 7L, WatcherAssessment.FullWalk(FullWalkReason.NO_EVENT_HOOK, 7)), + Triple( + FakeSignals(fence = Fence.NotReported), 7L, WatcherAssessment.FullWalk(FullWalkReason.FENCE_NOT_REPORTED, 7), + ), + Triple(FakeSignals(), null, WatcherAssessment.FullWalk(FullWalkReason.FIRST_REFRESH, 7)), + Triple(FakeSignals(changeCount = 8), 7L, WatcherAssessment.FullWalk(FullWalkReason.ROOTS_CHANGED, 8)), + ) + cases.forEach { (signals, previous, expected) -> + assertEquals(expected, assessFileWatcher(signals, previous), expected.reason.name) + } + } + + @Test + fun `a trusted watcher refreshes known covered folders from events and walks the others`() { + val known = Path.of("/project/solutions/a") + val new = Path.of("/project/solutions/b") + val outside = Path.of("/elsewhere/c") + val unresolved = Path.of("/project/solutions/missing") + val plan = planFolderRefresh( + listOf(known, new, outside, unresolved), + WatcherAssessment.Trusted(7, coverage), + refreshedBefore = setOf(known, outside, unresolved), + realPath = { it.takeUnless { path -> path == unresolved } }, + ) + assertEquals(FolderRefreshPlan(walk = listOf(new, outside, unresolved), fromEvents = listOf(known)), plan) + } + + @Test + fun `a full walk walks every folder`() { + val known = Path.of("/project/solutions/a") + val plan = planFolderRefresh( + listOf(known), WatcherAssessment.FullWalk(FullWalkReason.ROOTS_CHANGED, 8), setOf(known), { it }, + ) + assertEquals(FolderRefreshPlan(walk = listOf(known), fromEvents = emptyList()), plan) + } + + @Test + fun `without ordering across drives only folders on the fence's drive are covered`() { + val perDrive = WatchCoverage(listOf(Path.of("/project")), Path.of("/system/fence"), orderedAcrossDrives = false) + assertEquals(true, perDrive.covers(Path.of("/project/a"))) + // A relative path has no root, so it stands in for a fence on another drive. + assertEquals(false, perDrive.copy(fenceRoot = Path.of("relative/fence")).covers(Path.of("/project/a"))) + } + + @Test + fun `the log line names the mode and the cost`() { + val report = FolderRefreshReport(null, Duration.ofMillis(30)) + .withFolders(FolderRefreshPlan(walk = listOf(Path.of("/a")), fromEvents = listOf(Path.of("/b"), Path.of("/c"))), Duration.ofMillis(4)) + assertEquals( + "refreshed external changes using file watcher events: 2 folders from watcher events, 1 walked; " + + "watcher wait 30 ms, refresh 4 ms", + report.logLine(), + ) + assertEquals( + "refreshed external changes using a full walk because this is the first refresh: " + + "0 folders from watcher events, 0 walked; watcher wait 0 ms, refresh 0 ms", + FolderRefreshReport(FullWalkReason.FIRST_REFRESH, Duration.ZERO).logLine(), + ) + } + + private class FakeSignals( + private val operational: Boolean = true, + private val settled: Boolean = true, + private val fence: Fence = Fence.Reported(coverage), + private val changeCount: Long? = 7, + ) : FileWatcherSignals { + override fun isOperational() = operational + override fun awaitSettledRoots() = settled + override fun awaitFence() = fence + override fun changeCount() = changeCount + } + + private companion object { + val coverage = WatchCoverage(listOf(Path.of("/project"), Path.of("/library")), Path.of("/system/fence"), true) + } +} From 4b173102ac2795ba4ee00512cfeb85438ca8184b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergej=20Ko=C5=A1=C4=8Dejev?= Date: Tue, 17 Nov 2026 21:24:28 +0100 Subject: [PATCH 9/9] perf(daemon): refresh folders from native file watcher events Before each request, the daemon waits for the watcher to report a fence file, then refreshes known, watched folders from the watcher's events instead of walking them. It walks the folders when the watcher is not trusted; the daemon log names the mode and cost of each refresh. FolderRefresher (Adapter) refreshes the folders. It keeps the watcher's change count and the folders refreshed before as a private cache (`adapter-cache`). --- .../mops/daemon/ExternalProjectRefresh.kt | 31 +++--- .../mops/daemon/JetBrainsMpsAccess.kt | 2 +- .../daemon/filewatcher/FileWatcherFence.kt | 97 +++++++++++++++++++ .../daemon/filewatcher/FolderRefresher.kt | 59 +++++++++++ .../filewatcher/NativeFileWatcherProbe.kt | 68 +++++++++++++ .../filewatcher/folderRefreshExecutor.kt | 18 ++++ .../ExternalProjectRefreshSemanticsTest.kt | 20 +++- docs/daemon-request-concurrency.md | 4 + skills/mops-daemon/SKILL.md | 5 + 9 files changed, 287 insertions(+), 17 deletions(-) create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherFence.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefresher.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/NativeFileWatcherProbe.kt create mode 100644 daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshExecutor.kt diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt index 1c974cf1..fb551f9b 100644 --- a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefresh.kt @@ -3,13 +3,13 @@ package com.specificlanguages.mops.daemon import com.intellij.openapi.application.ApplicationManager import com.intellij.configurationStore.StoreReloadManager import com.intellij.openapi.vfs.LocalFileSystem -import com.intellij.openapi.vfs.VfsUtil +import com.specificlanguages.mops.daemon.filewatcher.FolderRefreshReport +import com.specificlanguages.mops.daemon.filewatcher.FolderRefresher import jetbrains.mps.classloading.ClassLoaderManager import jetbrains.mps.ide.platform.watching.ReloadManager import jetbrains.mps.project.MPSProject import jetbrains.mps.project.Project import jetbrains.mps.util.PathManager -import jetbrains.mps.vfs.refresh.DefaultCachingContext import kotlinx.coroutines.runBlocking import org.jetbrains.mps.openapi.module.SModuleReference import java.nio.file.Files @@ -17,7 +17,7 @@ import java.nio.file.Path /** * Adapter. Refreshes project files, the folders of source modules, and the archives of packaged modules, and replaces - * runtimes whose Java classpath contents changed between requests. + * runtimes whose Java classpath contents changed between requests. [FolderRefresher] refreshes the folders. * * Hides: how to make MPS see the changes that other programs made on disk to a project and the modules it loads. * @@ -25,44 +25,51 @@ import java.nio.file.Path * it, and `externalChangePolicy.kt` decides what changed; without it, a refresh would refresh every archive, load the * stored files of every folder, and replace every runtime. Not thread-safe: the request gate runs one refresh at a time. */ -internal class ExternalProjectRefresh(private val project: Project) { +internal class ExternalProjectRefresh(private val project: Project, private val logger: DaemonLogger) { private val classPathFingerprints = ClassPathFingerprints() + private val folderRefresher = FolderRefresher() private var baseline = RefreshBaseline(classPaths()) private val mpsHome = Path.of(PathManager.getHomePath()) - fun refresh() { + /** Refreshes external changes, logs how the folders were refreshed, and returns that report. */ + fun refresh(): FolderRefreshReport { val mpsProject = project as MPSProject val previous = baseline + val folders = folderRefresher.start() ApplicationManager.getApplication().invokeAndWait { val settings = Path.of(requireNotNull(mpsProject.project.basePath)).resolve(".mps") - mpsProject.fileSystem.getFile(settings.toString()).refresh(DefaultCachingContext(true, true)) + val settingsFolder = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(settings) + folders.refresh(listOfNotNull(settingsFolder?.toNioPath())) } // The component store reloads project membership separately from MPS's model/module reload sessions. runBlocking { StoreReloadManager.getInstance(mpsProject.project).reloadChangedStorageFiles() } lateinit var next: RefreshBaseline ApplicationManager.getApplication().invokeAndWait { - val loaded = refreshModuleFolders(previous.foldersWithStoredFilesLoaded) + val loaded = refreshModuleFolders(previous.foldersWithStoredFilesLoaded, folders::refresh) val archiveStamps = refreshModuleArchives(previous.archiveStamps) ReloadManager.getInstance().flush() val classPaths = replaceChangedRuntimes(previous.classPaths) next = RefreshBaseline(classPaths, archiveStamps, loaded) } baseline = next + val report = folders.finish() + logger.log(report.logLine()) + return report } /** - * Refreshes the local folders that modules are loaded from: project modules and the modules of libraries that point - * at source folders. The persistent VFS keeps records of these files across daemon restarts, so the first time a - * folder is seen, the files the VFS has stored under it are loaded into memory before the refresh; + * Refreshes the local folders that modules are loaded from with [refreshFolders]: project modules and the modules of + * libraries that point at source folders. The persistent VFS keeps records of these files across daemon restarts, so + * the first time a folder is seen, the files the VFS has stored under it are loaded into memory before the refresh; * docs/test-running-design.md explains why. Returns the folders whose stored files are loaded, [loaded] included. */ - private fun refreshModuleFolders(loaded: Set): Set { + private fun refreshModuleFolders(loaded: Set, refreshFolders: (List) -> Unit): Set { val folders = project.modelAccess.computeReadAction { moduleFolders(project, mpsHome) } .mapNotNull { LocalFileSystem.getInstance().findFileByNioFile(it) } .associateBy { it.toNioPath() } val toLoad = foldersToLoad(loaded, folders.keys.toList()) toLoad.forEach { loadStoredFiles(folders.getValue(it)) } - VfsUtil.markDirtyAndRefresh(false, true, true, *folders.values.toTypedArray()) + refreshFolders(folders.keys.toList()) return loaded + toLoad } diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/JetBrainsMpsAccess.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/JetBrainsMpsAccess.kt index 55d34496..9d723365 100644 --- a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/JetBrainsMpsAccess.kt +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/JetBrainsMpsAccess.kt @@ -37,7 +37,7 @@ class JetBrainsMpsAccess( private val persistence: PersistenceFacade = PersistenceFacade.getInstance(), private val writeTransaction: WriteTransaction = WriteTransaction(), ) : MpsAccess { - private val externalProjectRefresh = ExternalProjectRefresh(project) + private val externalProjectRefresh = ExternalProjectRefresh(project, logger) private val navigationTargets = NavigationTargetResolver(project, persistence) // An MpsRequestException is an expected client error, not a defect. Capture it inside the model action and rethrow diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherFence.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherFence.kt new file mode 100644 index 00000000..78c1d9b0 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FileWatcherFence.kt @@ -0,0 +1,97 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import com.intellij.openapi.application.PathManager +import com.intellij.openapi.util.io.FileUtil +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.vfs.impl.local.FileWatcher +import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.Path +import java.time.Duration +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.function.Consumer +import kotlin.io.path.createDirectories +import kotlin.io.path.deleteIfExists + +/** + * Adapter. Makes sure the native file watcher has reported every change made before [awaitReported] was called. There + * is no API to flush pending watcher events, and on macOS an event arrives up to about 300 ms after the change. + * `fsnotifier` reports events in order, so once it reports a change made by [awaitReported], it has reported every + * earlier change too. + * + * Hides: how mops learns that the watcher has caught up: the fence files and the private event hook it watches them + * through. + * + * Each call creates a fresh directory with a file in it under [root], a folder that is watched recursively, and waits + * until the watcher reports a path inside that directory. A fresh directory can only be named by events that happened + * after it was created. The raw watcher events are observed through `FileWatcher.myTestNotifier`, a private hook that + * the platform calls for every event; see the mps-api-research note native-file-watcher-in-headless-mps.md. + * + * Thread-safe: the watcher's thread reports events while a request thread waits in [awaitReported]. + */ +internal class FileWatcherFence private constructor(val root: Path) { + private val pending = ConcurrentHashMap() + + /** Returns `true` once the watcher reported the fence, or `false` after [timeout] or when it cannot be written. */ + fun awaitReported(timeout: Duration): Boolean { + val marker = root.resolve(UUID.randomUUID().toString()) + val reported = CountDownLatch(1) + pending[marker.toString()] = reported + try { + Files.createDirectory(marker) + Files.createFile(marker.resolve("fence")) + return reported.await(timeout.toMillis(), TimeUnit.MILLISECONDS) + } catch (_: IOException) { + return false + } finally { + pending.remove(marker.toString()) + deleteQuietly(marker) + } + } + + private fun onEvent(path: String) { + pending.forEach { (marker, reported) -> + if (path == marker || path.startsWith(marker + File.separator)) reported.countDown() + } + } + + private fun deleteQuietly(marker: Path) { + try { + marker.resolve("fence").deleteIfExists() + marker.deleteIfExists() + } catch (_: IOException) { + // A leftover fence directory is harmless: every call uses a new one. + } + } + + companion object { + /** The fence of this JVM, or `null` when the watcher's event hook is not available. */ + val instance: FileWatcherFence? by lazy { create() } + + private fun create(): FileWatcherFence? { + val fileWatcher = (LocalFileSystem.getInstance() as LocalFileSystemImpl).fileWatcher + val hook = try { + FileWatcher::class.java.getDeclaredField("myTestNotifier").apply { isAccessible = true } + } catch (_: ReflectiveOperationException) { + return null + } + if (hook.get(fileWatcher) != null) return null + // Reported paths are canonical and system-dependent, so the root is too. + val root = try { + Path.of(PathManager.getSystemPath(), "mops-file-watcher-fence").createDirectories().toRealPath() + } catch (_: IOException) { + return null + } + root.toFile().listFiles()?.forEach { FileUtil.delete(it) } + LocalFileSystem.getInstance().addRootToWatch(FileUtil.toSystemIndependentName(root.toString()), true) + val fence = FileWatcherFence(root) + hook.set(fileWatcher, Consumer(fence::onEvent)) + return fence + } + } +} diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefresher.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefresher.kt new file mode 100644 index 00000000..322ca117 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/FolderRefresher.kt @@ -0,0 +1,59 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import java.io.IOException +import java.nio.file.Path +import java.time.Duration + +/** + * Adapter. Refreshes folders in the VFS, from the native file watcher's events when `folderRefreshPolicy.kt` decides + * they can be relied on, and by walking the folders otherwise. + * + * Hides: how a refresh uses the native file watcher to refresh folders. + * + * Keeps a cache (`adapter-cache`): the watcher's change count at the latest refresh that finished, and the folders that + * refreshes have refreshed. Without it, every folder is walked. Not thread-safe: the request gate runs one refresh at a + * time. + */ +internal class FolderRefresher { + private var changeCount: Long? = null + private var refreshedFolders = emptySet() + + /** + * Starts a refresh. Waits until the watcher has reported every change made before this call, or decides to walk + * every folder. Must run outside the EDT. + */ + fun start(): Run { + val started = System.nanoTime() + val assessment = assessFileWatcher(NativeFileWatcherProbe.find(), changeCount) + return Run(assessment, Duration.ofNanos(System.nanoTime() - started)) + } + + /** One refresh. Call [finish] when the refresh succeeded, so that the next refresh compares with it. */ + inner class Run internal constructor(private val assessment: WatcherAssessment, watcherWait: Duration) { + private var refreshed = refreshedFolders + private var report = FolderRefreshReport((assessment as? WatcherAssessment.FullWalk)?.reason, watcherWait) + + /** Refreshes [folders] recursively. Must run on the EDT. */ + fun refresh(folders: List) { + val started = System.nanoTime() + val plan = planFolderRefresh(folders, assessment, refreshed, ::realPathOrNull) + refreshed += folders + executeFolderRefresh(plan) + report = report.withFolders(plan, Duration.ofNanos(System.nanoTime() - started)) + } + + /** Keeps this refresh for the next one to compare with, and returns how it refreshed folders. */ + fun finish(): FolderRefreshReport { + changeCount = assessment.changeCount + refreshedFolders = refreshed + return report + } + } +} + +private fun realPathOrNull(path: Path): Path? = + try { + path.toRealPath() + } catch (_: IOException) { + null + } diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/NativeFileWatcherProbe.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/NativeFileWatcherProbe.kt new file mode 100644 index 00000000..eed5a4c1 --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/NativeFileWatcherProbe.kt @@ -0,0 +1,68 @@ +package com.specificlanguages.mops.daemon.filewatcher + +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl +import com.intellij.openapi.vfs.local.PluggableFileWatcher +import java.nio.file.Path +import java.time.Duration + +/** + * Adapter. Answers [assessFileWatcher] from the platform's file watcher, the plugin's `HeadlessNativeFileWatcher`, and + * the [FileWatcherFence]. Must run outside the EDT. + * + * Hides: how the daemon reads the state of the native file watcher. + * + * Breaks `connascence-in-types`: the plugin class loader loads `HeadlessNativeFileWatcher`, so the daemon cannot share + * a type with it and calls it by its class name and method names (`changeCount`, `recursiveRoots`), as `JavaParser` + * calls the plugin's `JavaParserBridge`. + */ +internal class NativeFileWatcherProbe private constructor(private val headless: PluggableFileWatcher) : FileWatcherSignals { + private val fileWatcher = (LocalFileSystem.getInstance() as LocalFileSystemImpl).fileWatcher + + // Creating the fence adds a watch root, so it is created before waiting for the roots to settle. + private val fence = if (fileWatcher.isOperational) FileWatcherFence.instance else null + + override fun isOperational(): Boolean = fileWatcher.isOperational + + override fun awaitSettledRoots(): Boolean { + val deadline = System.nanoTime() + ROOTS_TIMEOUT.toNanos() + while (fileWatcher.isSettingRoots) { + if (System.nanoTime() > deadline) return false + Thread.sleep(POLL_MILLIS) + } + return true + } + + override fun awaitFence(): FileWatcherSignals.Fence = when { + fence == null -> FileWatcherSignals.Fence.Unavailable + fence.awaitReported(FENCE_TIMEOUT) -> FileWatcherSignals.Fence.Reported(coverage(fence)) + else -> FileWatcherSignals.Fence.NotReported + } + + override fun changeCount(): Long? { + // The watcher reports failures as notifications that are delivered on the EDT. + ApplicationManager.getApplication().invokeAndWait {} + return headless.javaClass.getMethod("changeCount").invoke(headless) as Long? + } + + private fun coverage(fence: FileWatcherFence) = WatchCoverage( + recursiveRoots = (headless.javaClass.getMethod("recursiveRoots").invoke(headless) as List<*>) + .map { Path.of(it as String) }, + fenceRoot = fence.root, + // On Windows, fsnotifier watches each drive in its own thread, so it keeps the order of events only within a drive. + orderedAcrossDrives = !System.getProperty("os.name").startsWith("Windows"), + ) + + companion object { + private const val CLASS_NAME = "com.specificlanguages.mops.daemon.plugin.HeadlessNativeFileWatcher" + private val FENCE_TIMEOUT: Duration = Duration.ofSeconds(2) + private val ROOTS_TIMEOUT: Duration = Duration.ofSeconds(10) + private const val POLL_MILLIS = 10L + + /** The probe of the plugin's watcher, or `null` when the plugin did not register it. */ + fun find(): NativeFileWatcherProbe? = + PluggableFileWatcher.EP_NAME.extensionList.firstOrNull { it.javaClass.name == CLASS_NAME } + ?.let(::NativeFileWatcherProbe) + } +} diff --git a/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshExecutor.kt b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshExecutor.kt new file mode 100644 index 00000000..a939733f --- /dev/null +++ b/daemon/src/main/kotlin/com/specificlanguages/mops/daemon/filewatcher/folderRefreshExecutor.kt @@ -0,0 +1,18 @@ +/** + * Adapter. Hides: how the VFS refreshes a folder, by walking it or from the native file watcher's events. + */ +package com.specificlanguages.mops.daemon.filewatcher + +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.vfs.VfsUtil +import java.nio.file.Path + +/** Refreshes the folders of [plan] recursively. A folder that the VFS does not know is skipped. Must run on the EDT. */ +internal fun executeFolderRefresh(plan: FolderRefreshPlan) { + val walk = virtualFiles(plan.walk) + if (walk.isNotEmpty()) VfsUtil.markDirtyAndRefresh(false, true, true, *walk.toTypedArray()) + val fromEvents = virtualFiles(plan.fromEvents) + if (fromEvents.isNotEmpty()) LocalFileSystem.getInstance().refreshFiles(fromEvents, false, true, null) +} + +private fun virtualFiles(folders: List) = folders.mapNotNull { LocalFileSystem.getInstance().findFileByNioFile(it) } diff --git a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt index 3dcf58bc..4a2f7a33 100644 --- a/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt +++ b/daemon/src/test/kotlin/com/specificlanguages/mops/daemon/ExternalProjectRefreshSemanticsTest.kt @@ -10,8 +10,14 @@ import kotlin.io.path.readText import kotlin.io.path.writeText import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull -/** A refresh sees an external edit of a model file made immediately before it. */ +/** + * A refresh sees an external edit of a model file made immediately before it, also when it relies on the native file + * watcher instead of walking the folders. On macOS and on Linux x86-64 the watcher must be in use, so these tests + * exercise the fence. + */ class ExternalProjectRefreshSemanticsTest { @Test @@ -44,16 +50,17 @@ class ExternalProjectRefreshSemanticsTest { node: MpsRead.() -> MpsNodeJson, ) { val access = SharedMpsEnvironment.mpsAccess(project) - val refresh = ExternalProjectRefresh(project) - refresh.refresh() + val refresh = ExternalProjectRefresh(project, DaemonLogger()) + assertNotNull(refresh.refresh().fullWalkReason, "the first refresh walks every folder") var previousName = originalName repeat(EDITS) { index -> val name = "$originalName$index" model.writeText(model.readText().replace("value=\"$previousName\"", "value=\"$name\"")) previousName = name - refresh.refresh() + val report = refresh.refresh() + if (watcherExpected) assertNull(report.fullWalkReason, "edit $index: the refresh relies on the file watcher") assertEquals(name, propertyValue(access.read(node), "name"), "edit $index is visible after the refresh") } } @@ -61,6 +68,11 @@ class ExternalProjectRefreshSemanticsTest { private companion object { const val EDITS = 20 + // Every supported MPS version ships fsnotifier for macOS and for Linux on x86-64. + val watcherExpected = System.getProperty("os.name").let { os -> + os.startsWith("Mac") || os.startsWith("Linux") && System.getProperty("os.arch") in setOf("amd64", "x86_64") + } + const val STRUCTURE_MODEL_NAME = "com.specificlanguages.json.structure" const val STRUCTURE_MODEL_PATH = "languages/com.specificlanguages.json/models/com.specificlanguages.json.structure.mps" diff --git a/docs/daemon-request-concurrency.md b/docs/daemon-request-concurrency.md index 50f28b75..166c99bd 100644 --- a/docs/daemon-request-concurrency.md +++ b/docs/daemon-request-concurrency.md @@ -9,6 +9,10 @@ started share the refreshed state and run concurrently. The batch ends at the fi request that arrived during the refresh, so every request sees the external changes made before it arrived. Later requests wait for another refresh after the active batch finishes. There is no batching delay. +A refresh relies on the events of the native file watcher where it can, and walks the folders otherwise. +`FullWalkReason` lists when it walks every folder. Each refresh writes a line to the daemon log that names its mode and +its cost. + ```text refresh → [list, get-node, find] → refresh → edit → refresh → [list, find] ping → pong (independent of project admission) diff --git a/skills/mops-daemon/SKILL.md b/skills/mops-daemon/SKILL.md index f94283fe..df891f0a 100644 --- a/skills/mops-daemon/SKILL.md +++ b/skills/mops-daemon/SKILL.md @@ -108,6 +108,11 @@ active request. `MOPS_DAEMON_JAVA_OPTIONS=-Xmx8g`. Test workers started by the daemon inherit them. Without it, the JVM picks its default maximum heap, a quarter of physical memory. +Before each request, the daemon reads external file changes from the native file watcher, and walks the project and +module folders when it cannot rely on the watcher. Each refresh writes a line to the daemon log that names how it went +and what it cost. If a request misses an external edit, start the daemon with +`MOPS_DAEMON_JAVA_OPTIONS=-Didea.filewatcher.disabled=true`: then every refresh walks the folders. + Test runs keep the IntelliJ system directory (VFS and indexes) of the test worker between runs in the workspace's `test-worker-system` directory, so a run does not index the MPS distribution again. A run that does not end cleanly (timed out, cancelled, or a crashed worker) deletes it, and the next run indexes again. The directory is safe to delete