From a3d21886e95483f6b3e9cca137d8725a3418fc7a Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:38:59 +0000 Subject: [PATCH 01/12] ADFA-6731: Refuse and close indexes registered after the registry closes --- .../indexing/service/IndexRegistry.kt | 57 ++++++++++++++++--- .../service/IndexRegistryClosedException.kt | 11 ++++ .../indexing/service/IndexRegistryTest.kt | 40 +++++++++++++ 3 files changed, 100 insertions(+), 8 deletions(-) create mode 100644 lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt index 70f2cded18..fc38de171a 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt @@ -16,23 +16,45 @@ data class IndexKey( /** * Central registry where [IndexingService]s publish their indexes * and consumers (LSPs, etc.) retrieve them. + * + * Once closed, it refuses new indexes and [require] throws [IndexRegistryClosedException], so work + * for an ended project session stops instead of opening indexes nothing would close. */ class IndexRegistry : Closeable { private val indexes = ConcurrentHashMap() private val listeners = ConcurrentHashMap Unit>>() + @Volatile + private var closed = false + + /** Whether [close] has been called. */ + val isClosed: Boolean + get() = closed + /** * Register an index. Replaces any previously registered index * with the same key. * * If there are listeners waiting for this key, they are notified * immediately. + * + * @throws IndexRegistryClosedException if the registry is closed; [index] is closed first. */ fun register( key: IndexKey, index: T, ) { + if (closed) { + (index as? Closeable)?.close() + throw closedException(key) + } + val old = indexes.put(key.name, index) + if (closed) { + // close() may have drained the map before this entry landed; whoever removes it closes it. + if (indexes.remove(key.name, index)) (index as? Closeable)?.close() + throw closedException(key) + } // Close the old index if it's Closeable if (old is Closeable && old !== index) { @@ -59,13 +81,22 @@ class IndexRegistry : Closeable { * left with a closed index. [create] runs only when no index is registered, and listeners are * notified only when it ran. [create] runs inside the registry's map update, so it must not call * back into this registry. + * + * @throws IndexRegistryClosedException if the registry is closed; [create] is then not called. */ fun registerIfAbsent( key: IndexKey, create: () -> T, ): T { + if (closed) throw closedException(key) + var created: T? = null val index = indexes.computeIfAbsent(key.name) { create().also { created = it } } + if (closed) { + // close() may have drained the map before this entry landed; whoever removes it closes it. + if (indexes.remove(key.name, index)) (index as? Closeable)?.close() + throw closedException(key) + } created?.let { notifyListeners(key, it) } @@ -81,12 +112,19 @@ class IndexRegistry : Closeable { /** * Retrieve an index, throwing if not available. + * + * @throws IndexRegistryClosedException if the registry is closed. + * @throws IllegalStateException if the registry is open but nothing is registered for [key]. */ fun require(key: IndexKey): T = - get(key) ?: throw IllegalStateException( - "Index '${key.name}' is not registered. " + - "Has the corresponding IndexingService been initialized?", - ) + get(key) ?: if (closed) { + throw closedException(key) + } else { + throw IllegalStateException( + "Index '${key.name}' is not registered. " + + "Has the corresponding IndexingService been initialized?", + ) + } /** * Execute a block if the index is available. @@ -138,13 +176,16 @@ class IndexRegistry : Closeable { fun registeredKeys(): Set = indexes.keys.toSet() /** - * Close and remove all registered indexes. + * Close and remove all registered indexes, and refuse new ones from now on. */ override fun close() { - indexes.values.forEach { index -> - if (index is Closeable) index.close() + closed = true + // Removed one by one so an index a racing registerIfAbsent adds is closed exactly once. + for (name in indexes.keys.toList()) { + (indexes.remove(name) as? Closeable)?.close() } - indexes.clear() listeners.clear() } + + private fun closedException(key: IndexKey<*>) = IndexRegistryClosedException("Index registry is closed; cannot provide '${key.name}'") } diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt new file mode 100644 index 0000000000..2d5de12099 --- /dev/null +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryClosedException.kt @@ -0,0 +1,11 @@ +package org.appdevforall.codeonthego.indexing.service + +/** + * Thrown when an index is requested from, or registered with, an [IndexRegistry] that has been closed. + * + * Its project session has ended, so callers treat it as an expected end of their work rather than + * a failure. + */ +class IndexRegistryClosedException( + message: String, +) : IllegalStateException(message) diff --git a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt index 9244ce421b..b933f4513c 100644 --- a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt +++ b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt @@ -1,6 +1,7 @@ package org.appdevforall.codeonthego.indexing.service import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -199,6 +200,45 @@ class IndexRegistryTest { assertThat(received).containsExactly("created") } + @Test + fun `registerIfAbsent after close does not create and throws`() { + val registry = IndexRegistry() + registry.close() + var created = false + + assertThrows(IndexRegistryClosedException::class.java) { + registry.registerIfAbsent(keyA) { + created = true + "created" + } + } + + assertThat(created).isFalse() + assertThat(registry.get(keyA)).isNull() + } + + @Test + fun `register after close closes the given index and throws`() { + val registry = IndexRegistry() + registry.close() + val keyC = IndexKey("index-c") + val index = CloseableValue() + + assertThrows(IndexRegistryClosedException::class.java) { registry.register(keyC, index) } + + assertThat(index.closed).isTrue() + assertThat(registry.get(keyC)).isNull() + } + + @Test + fun `require after close throws the closed exception`() { + val registry = IndexRegistry() + registry.register(keyA, "a") + registry.close() + + assertThrows(IndexRegistryClosedException::class.java) { registry.require(keyA) } + } + class CloseableValue : Closeable { var closed = false From 6744c7a5594659a2de29e828fa312a64f022a5e3 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:41:34 +0000 Subject: [PATCH 02/12] ADFA-6731: Log use of a closed index at DEBUG once its session has ended --- .../indexing/IndexSessionLifetime.kt | 21 ++++++++++++++ .../codeonthego/indexing/SQLiteIndex.kt | 10 ++++++- .../indexing/service/IndexRegistry.kt | 6 +++- .../service/IndexingServiceManager.kt | 1 + .../indexing/SQLiteIndexUseAfterCloseTest.kt | 28 ++++++++++++++++++- .../service/IndexingServiceManagerTest.kt | 16 +++++++++++ .../indexing/jvm/JarIndexingService.kt | 5 ++-- .../indexing/jvm/JvmSymbolIndex.kt | 4 +++ .../indexing/jvm/KtFileMetadataIndex.kt | 6 +++- .../jvm/JarIndexingServiceProgressTest.kt | 5 ++-- 10 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt new file mode 100644 index 0000000000..54bab966bd --- /dev/null +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/IndexSessionLifetime.kt @@ -0,0 +1,21 @@ +package org.appdevforall.codeonthego.indexing + +/** + * Marks whether the project session that owns a set of indexes has ended. + * + * Indexes of an ended session are expected to be used after close while the session's remaining + * work winds down, so they log that at DEBUG; a live session's use after close is a bug and logs ERROR. + */ +class IndexSessionLifetime { + @Volatile + private var ended = false + + /** Whether [end] has been called. */ + val isEnded: Boolean + get() = ended + + /** Ends the session; idempotent and never blocks. */ + fun end() { + ended = true + } +} diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt index ac03e05199..4004ea57ae 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndex.kt @@ -101,6 +101,8 @@ import kotlin.collections.iterator * @param batchSize Number of rows per INSERT transaction. * @param sourceIdChunkSize Max number of `_source_id` placeholders per source-scoped statement. * See [SOURCE_ID_CHUNK_SIZE]. + * @param lifetime The project session owning this index; once it has ended, use after close is + * expected and logged at DEBUG instead of ERROR. */ class SQLiteIndex( override val descriptor: IndexDescriptor, @@ -110,6 +112,7 @@ class SQLiteIndex( override val name: String = "sqlite:${descriptor.name}", private val batchSize: Int = 500, @param:VisibleForTesting internal val sourceIdChunkSize: Int = SOURCE_ID_CHUNK_SIZE, + private val lifetime: IndexSessionLifetime? = null, ) : Index, PackageTree { companion object { @@ -560,12 +563,17 @@ class SQLiteIndex( /* * A closed index answers with empty results, which callers cannot tell from a genuinely empty - * index, so the first such call is logged with its stack to name whoever still holds it. + * index, so the first such call is logged with its stack to name whoever still holds it. Once the + * owning session has ended its remaining work is expected to hit closed indexes, so that is DEBUG. * Called under [mutex]. */ private fun reportUseAfterClose(operation: String) { if (useAfterCloseReported) return useAfterCloseReported = true + if (lifetime?.isEnded == true) { + log.debug("Index '{}' used after its session ended, in {}; returning an empty result", name, operation) + return + } log.error( "Index '{}' used after close in {}; returning an empty result", name, diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt index fc38de171a..5d09a3d7be 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt @@ -1,5 +1,6 @@ package org.appdevforall.codeonthego.indexing.service +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import java.io.Closeable import java.util.concurrent.ConcurrentHashMap @@ -20,7 +21,10 @@ data class IndexKey( * Once closed, it refuses new indexes and [require] throws [IndexRegistryClosedException], so work * for an ended project session stops instead of opening indexes nothing would close. */ -class IndexRegistry : Closeable { +class IndexRegistry( + /** The project session these indexes belong to; ended when that session closes. */ + val lifetime: IndexSessionLifetime = IndexSessionLifetime(), +) : Closeable { private val indexes = ConcurrentHashMap() private val listeners = ConcurrentHashMap Unit>>() diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt index c6dacbd9b9..e04ef5746e 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt @@ -177,6 +177,7 @@ class IndexingServiceManager( */ override fun close() { log.info("Shutting down indexing services") + registry.lifetime.end() // Called from ProjectHandlerActivity.onPause on the main thread, so the // closes (SERVICE_CLOSE_TIMEOUT only bounds cooperative ones; SQLiteIndex and diff --git a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndexUseAfterCloseTest.kt b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndexUseAfterCloseTest.kt index f833c9b34f..db406f59af 100644 --- a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndexUseAfterCloseTest.kt +++ b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/SQLiteIndexUseAfterCloseTest.kt @@ -94,13 +94,39 @@ class SQLiteIndexUseAfterCloseTest { assertThat(errorsNamingIndex()).isEmpty() } - private fun newIndex() = + @Test + fun `use after close in an ended session logs one debug and no error`(): Unit = + runBlocking { + val index = newIndex(IndexSessionLifetime().apply { end() }) + index.close() + + index.query(IndexQuery(sourceIds = null, limit = 0)).toList() + index.insert(Entry("k", "s")) + + assertThat(errorsNamingIndex()).isEmpty() + assertThat(captured.filter { it.level == Level.DEBUG && INDEX_NAME in it.message }).hasSize(1) + } + + @Test + fun `use after close in a live session still logs one error`(): Unit = + runBlocking { + val index = newIndex(IndexSessionLifetime()) + index.close() + + index.query(IndexQuery(sourceIds = null, limit = 0)).toList() + index.insert(Entry("k", "s")) + + assertThat(errorsNamingIndex()).hasSize(1) + } + + private fun newIndex(lifetime: IndexSessionLifetime? = null) = SQLiteIndex( descriptor = descriptor, context = context, dbName = DB_NAME, formatVersion = 1, name = INDEX_NAME, + lifetime = lifetime, ) private fun errorsNamingIndex() = captured.filter { it.level == Level.ERROR && INDEX_NAME in it.message } diff --git a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt index 742ef82e00..4d875e7224 100644 --- a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt +++ b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt @@ -118,6 +118,22 @@ class IndexingServiceManagerTest { manager.close() } + @Test + fun `close ends the session lifetime before it returns`() { + val manager = IndexingServiceManager() + + manager.close() + + assertThat(manager.registry.lifetime.isEnded).isTrue() + } + + @Test + fun `a new manager's lifetime is live after the previous manager closed`() { + IndexingServiceManager().close() + + assertThat(IndexingServiceManager().registry.lifetime.isEnded).isFalse() + } + @Test fun `close after close does not throw`() { val manager = IndexingServiceManager() diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt index 2adcb41441..e15731e0e1 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingService.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.service.IndexKey import org.appdevforall.codeonthego.indexing.service.IndexRegistry import org.appdevforall.codeonthego.indexing.service.IndexingProgressTracker @@ -58,7 +59,7 @@ abstract class JarIndexingService( private val workspaceSupplier: () -> Workspace? = { ProjectManagerImpl.getInstance().workspace }, private val unreadableJarReporter: (List) -> Unit = ::reportUnreadableClasspathJars, private val unreadableJarFilter: (Collection) -> List = { it.toList() }, - private val indexFactory: (Context, String, String) -> JvmSymbolIndex = JvmSymbolIndex::createSqliteIndex, + private val indexFactory: (Context, String, String, IndexSessionLifetime?) -> JvmSymbolIndex = JvmSymbolIndex::createSqliteIndex, ) : IndexingService { companion object { private val log = LoggerFactory.getLogger(JarIndexingService::class.java) @@ -90,7 +91,7 @@ abstract class JarIndexingService( ) override suspend fun initialize(registry: IndexRegistry) { - val jvmIndex = indexFactory(context, dbName, indexName) + val jvmIndex = indexFactory(context, dbName, indexName, registry.lifetime) this.jarIndex = jvmIndex registry.register(indexKey, jvmIndex) diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt index 4cac5a5ed8..0b0061dfc7 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/JvmSymbolIndex.kt @@ -6,6 +6,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.joinAll import org.appdevforall.codeonthego.indexing.FilteredIndex +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.SQLiteIndex import org.appdevforall.codeonthego.indexing.api.Index import org.appdevforall.codeonthego.indexing.api.IndexQueryBuilder @@ -69,11 +70,13 @@ open class JvmSymbolIndex( * @param context The context to use for accessing the SQLite database. * @param dbName The name of the database. Defaults to [DB_NAME_DEFAULT]. * @param indexName The name of the index. Defaults to [INDEX_NAME_LIBRARY]. + * @param lifetime The project session owning the index, or null if it has none. */ fun createSqliteIndex( context: Context, dbName: String, indexName: String, + lifetime: IndexSessionLifetime? = null, ): JvmSymbolIndex { val cache = SQLiteIndex( @@ -82,6 +85,7 @@ open class JvmSymbolIndex( dbName = dbName, formatVersion = FORMAT_VERSION, name = indexName, + lifetime = lifetime, ) val indexer = BackgroundIndexer(cache) diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt index 02a7bd890b..df7a82b158 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KtFileMetadataIndex.kt @@ -1,6 +1,7 @@ package org.appdevforall.codeonthego.indexing.jvm import android.content.Context +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.SQLiteIndex import org.appdevforall.codeonthego.indexing.api.Index import org.appdevforall.codeonthego.indexing.api.indexQuery @@ -19,11 +20,13 @@ class KtFileMetadataIndex( * Creates a [KtFileMetadataIndex] backed by a SQLite database. * * The [context] is required by the AndroidX SQLite helpers even for in-memory - * databases; it is not used for any file I/O. + * databases; it is not used for any file I/O. [lifetime] is the project session owning the + * index, or null if it has none. */ fun sqliteBacked( context: Context, dbName: String? = null, + lifetime: IndexSessionLifetime? = null, ): KtFileMetadataIndex = KtFileMetadataIndex( SQLiteIndex( @@ -32,6 +35,7 @@ class KtFileMetadataIndex( dbName = dbName, formatVersion = JvmSymbolIndex.FORMAT_VERSION, name = "kt-file-metadata", + lifetime = lifetime, ), ) } diff --git a/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingServiceProgressTest.kt b/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingServiceProgressTest.kt index 537eb1dbb4..6b333c2a50 100644 --- a/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingServiceProgressTest.kt +++ b/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/JarIndexingServiceProgressTest.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.IndexSessionLifetime import org.appdevforall.codeonthego.indexing.api.Index import org.appdevforall.codeonthego.indexing.service.IndexKey import org.appdevforall.codeonthego.indexing.service.IndexRegistry @@ -57,7 +58,7 @@ class JarIndexingServiceProgressTest { val service = TestService( jars = setOf(jar("a.jar"), jar("b.jar"), jar("c.jar")), - indexFactory = { _, _, _ -> JvmSymbolIndex(backing, BackgroundIndexer(backing)) }, + indexFactory = { _, _, _, _ -> JvmSymbolIndex(backing, BackgroundIndexer(backing)) }, ) val counted = @@ -161,7 +162,7 @@ class JarIndexingServiceProgressTest { private inner class TestService( private val jars: Set, private val onComplete: suspend () -> Unit = {}, - indexFactory: (Context, String, String) -> JvmSymbolIndex = JvmSymbolIndex::createSqliteIndex, + indexFactory: (Context, String, String, IndexSessionLifetime?) -> JvmSymbolIndex = JvmSymbolIndex::createSqliteIndex, ) : JarIndexingService(context, tracker, workspaceSupplier = { mockk() }, indexFactory = indexFactory) { var stateWhileCompleting: IndexingState? = null From 940a314bb7a370c8ac20003e85debc661a955c53 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:43:19 +0000 Subject: [PATCH 03/12] ADFA-6731: Stop indexing setup quietly when the session closes, and retry a setup that found no services --- .../service/IndexingServiceManager.kt | 17 +++- .../service/IndexingServiceManagerTest.kt | 79 +++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt index e04ef5746e..ee88edaa82 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManager.kt @@ -243,12 +243,21 @@ class IndexingServiceManager( } } - /** Returns false when setup was skipped because the previous close has not finished. */ + /** + * Returns false when setup did not happen, so the next [onProjectSynced] retries it: the previous + * close has not finished, no service is registered yet, or this manager closed meanwhile. + */ private suspend fun initializeServices(): Boolean { if (!awaitPendingClose()) return false - log.info("Initializing {} indexing services", services.size) val allServices = allServices() + if (allServices.isEmpty()) { + // A sync can reach a new manager before its services register; latching here would skip them. + log.info("No indexing services registered yet; initializing on the next sync") + return false + } + log.info("Initializing {} indexing services", allServices.size) + for (service in allServices) { try { service.initialize(registry) @@ -257,6 +266,10 @@ class IndexingServiceManager( service.id, service.providedKeys.joinToString { it.name }, ) + } catch (e: IndexRegistryClosedException) { + // Returning true would set initialized after close() reset it. + log.info("Indexing session closed while initializing '{}'; stopping", service.id) + return false } catch (e: Exception) { log.error("Failed to initialize service: {}", service.id, e) } diff --git a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt index 4d875e7224..77824ab804 100644 --- a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt +++ b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexingServiceManagerTest.kt @@ -1,18 +1,40 @@ package org.appdevforall.codeonthego.indexing.service import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.logging.provider.IdeLogRouter import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 +import org.slf4j.event.Level +import java.util.Collections import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @RunWith(JUnit4::class) class IndexingServiceManagerTest { + private val errors: MutableList = Collections.synchronizedList(mutableListOf()) + private val sink = + IdeLogRouter.ExternalSink { level, _, message, _ -> + if (level == Level.ERROR) errors += message + } + + @Before + fun installSink() { + IdeLogRouter.addSink(sink) + } + + @After + fun removeSink() { + IdeLogRouter.removeSink(sink) + } + class TestService( override val id: String, ) : IndexingService { @@ -272,6 +294,58 @@ class IndexingServiceManagerTest { } } + @Test + fun `a close during initialization stops quietly`() { + val calls = AtomicInteger() + val manager = IndexingServiceManager() + repeat(2) { n -> + manager.register( + object : IndexingService { + override val id = "closing-$n" + override val providedKeys = emptyList>() + + override suspend fun initialize(registry: IndexRegistry) { + calls.incrementAndGet() + registry.close() + registry.register(IndexKey("k$n"), "v") + } + }, + ) + } + + manager.onProjectSynced() + Thread.sleep(SETTLE_MILLIS) + + assertThat(calls.get()).isEqualTo(1) + assertThat(errors).isEmpty() + manager.close() + runBlocking { withTimeout(5_000) { IndexingServiceManager.awaitPendingClose() } } + } + + @Test + fun `a sync with no services does not latch initialized`() { + val manager = IndexingServiceManager() + manager.onProjectSynced() + Thread.sleep(SETTLE_MILLIS) + + val initialized = CountDownLatch(1) + manager.register( + object : IndexingService { + override val id = "late" + override val providedKeys = emptyList>() + + override suspend fun initialize(registry: IndexRegistry) { + initialized.countDown() + } + }, + ) + manager.onProjectSynced() + + assertThat(initialized.await(5, TimeUnit.SECONDS)).isTrue() + manager.close() + runBlocking { withTimeout(5_000) { IndexingServiceManager.awaitPendingClose() } } + } + /** A manager whose only service blocks in close() until [release] opens. */ private fun blockingManager(release: CountDownLatch) = IndexingServiceManager().apply { @@ -299,4 +373,9 @@ class IndexingServiceManagerTest { closer.join(millis) return !closer.isAlive } + + private companion object { + /** Long enough for a launched initialization to finish. */ + const val SETTLE_MILLIS = 200L + } } From d53619050ef2e889659a2478f1843d84a3a18f85 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:44:44 +0000 Subject: [PATCH 04/12] ADFA-6731: Record the indexing close before a new manager can be created --- .../androidide/projects/ProjectManagerImpl.kt | 20 ++++++++++++------- ...ctManagerImplIndexingServiceManagerTest.kt | 14 +++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt index fa43658911..094c3c695f 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt @@ -96,6 +96,10 @@ class ProjectManagerImpl : _indexingServiceManager ?: IndexingServiceManager().also { _indexingServiceManager = it } } + /** The indexing service manager of the current project session, or null if none exists; never creates one. */ + val currentIndexingServiceManager: IndexingServiceManager? + get() = synchronized(indexingServiceManagerLock) { _indexingServiceManager } + @Volatile internal var pluginProjectCached: Boolean? = null @@ -265,13 +269,15 @@ class ProjectManagerImpl : this.workspace = null pluginProjectCached = null - // Closed outside the lock: close() blocks until every service has shut down, and a worker - // thread reading the manager meanwhile must not wait on that. - val indexingServiceManager = - synchronized(indexingServiceManagerLock) { - _indexingServiceManager.also { _indexingServiceManager = null } - } - indexingServiceManager?.close() + /* + * Closed inside the lock, so the getter cannot create the next manager before this close is + * recorded as pending, which the next manager waits for. Safe to hold: close() only ends the + * session lifetime and launches the actual close in the background. + */ + synchronized(indexingServiceManagerLock) { + _indexingServiceManager?.close() + _indexingServiceManager = null + } (this.androidBuildVariants as? MutableMap?)?.clear() } diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/ProjectManagerImplIndexingServiceManagerTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/ProjectManagerImplIndexingServiceManagerTest.kt index ff7cd1ad41..92d156df19 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/ProjectManagerImplIndexingServiceManagerTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/ProjectManagerImplIndexingServiceManagerTest.kt @@ -51,6 +51,20 @@ class ProjectManagerImplIndexingServiceManagerTest { manager.destroy() } + @Test + fun `currentIndexingServiceManager is null after destroy and stays null`() { + val manager = ProjectManagerImpl() + manager.indexingServiceManager + manager.destroy() + + assertThat(manager.currentIndexingServiceManager).isNull() + assertThat(manager.currentIndexingServiceManager).isNull() + + val created = manager.indexingServiceManager + assertThat(manager.currentIndexingServiceManager).isSameInstanceAs(created) + manager.destroy() + } + private companion object { const val ROUNDS = 50 const val THREADS = 16 From cd29e80359e2e9082082f4121916a4780399ec8a Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:47:58 +0000 Subject: [PATCH 05/12] ADFA-6731: Bind each Kotlin project update to one indexing manager --- .../androidide/lsp/kotlin/CompilerSession.kt | 23 ++++++++--- .../lsp/kotlin/KotlinLanguageServer.kt | 17 +++++--- .../lsp/kotlin/compiler/KotlinProjectModel.kt | 38 ++++++------------ .../lsp/kotlin/CompilerSessionTest.kt | 40 ++++++++++++++++++- .../compiler/KotlinProjectModelIndexTest.kt | 26 ++++++++++++ 5 files changed, 107 insertions(+), 37 deletions(-) create mode 100644 lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt index bc39033c06..02f64da8f7 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt @@ -8,12 +8,19 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch +import org.appdevforall.codeonthego.indexing.service.IndexingServiceManager import org.slf4j.LoggerFactory /** The steps [CompilerSession] runs for each project update, on its own thread. */ internal interface CompilerLifecycle { + /** Returns the indexing manager of the current project session. */ + fun currentManager(): IndexingServiceManager + /** Runs on every project update, before its layout is compared. */ - fun prepare(workspace: Workspace) + fun prepare( + workspace: Workspace, + manager: IndexingServiceManager, + ) /** Returns the module layout of [workspace]. */ fun layoutOf(workspace: Workspace): KotlinModuleLayout @@ -21,10 +28,11 @@ internal interface CompilerLifecycle { /** Waits for the previous compiler to finish closing; returns false if it is still closing. */ fun awaitClosed(): Boolean - /** Builds a compiler for [layout]. */ + /** Builds a compiler for [layout] against [manager]'s indexes. */ fun build( workspace: Workspace, layout: KotlinModuleLayout, + manager: IndexingServiceManager, ): C /** Closes [compiler] without blocking the caller. */ @@ -102,9 +110,14 @@ internal class CompilerSession( * prepare opens the source indexes, which a previous project's compiler may still hold open. * The update cannot be cancelled while it blocks, so shutdown is re-checked after each wait: * past it, prepare would revive the closed project's indexing state. + * + * The manager is taken once, under the same lock as that check: the editor stops this session + * before it destroys the project, so an update past the check only ever sees the closing + * session's manager, never the next one's. */ - if (!awaitClosed() || isStopped()) return - lifecycle.prepare(workspace) + if (!awaitClosed()) return + val manager = synchronized(lock) { if (isShutDown) null else lifecycle.currentManager() } ?: return + lifecycle.prepare(workspace, manager) val layout = lifecycle.layoutOf(workspace) if (isStopped()) return @@ -118,7 +131,7 @@ internal class CompilerSession( detachCurrent() if (!awaitClosed() || isStopped()) return - val built = lifecycle.build(workspace, layout) + val built = lifecycle.build(workspace, layout, manager) val published = synchronized(lock) { if (!isShutDown) current = built diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt index 185a11857b..4e9e062c0b 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt @@ -213,10 +213,14 @@ class KotlinLanguageServer : ILanguageServer { } private inner class ProjectCompilerLifecycle : CompilerLifecycle { - override fun prepare(workspace: Workspace) { + override fun currentManager() = ProjectManagerImpl.getInstance().indexingServiceManager + + override fun prepare( + workspace: Workspace, + manager: IndexingServiceManager, + ) { val context = BaseApplication.baseInstance - val indexingServiceManager = ProjectManagerImpl.getInstance().indexingServiceManager - val indexingRegistry = indexingServiceManager.registry + val indexingRegistry = manager.registry // Once per project: replacing them would close the instances a live session reads. indexingRegistry.registerIfAbsent(KT_SOURCE_FILE_INDEX_KEY) { @@ -224,17 +228,19 @@ class KotlinLanguageServer : ILanguageServer { context = context, dbName = KT_SOURCE_FILE_INDEX_KEY.name, indexName = KT_SOURCE_FILE_INDEX_KEY.name, + lifetime = indexingRegistry.lifetime, ) } indexingRegistry.registerIfAbsent(KT_SOURCE_FILE_META_INDEX_KEY) { KtFileMetadataIndex.sqliteBacked( context = context, dbName = KT_SOURCE_FILE_META_INDEX_KEY.name, + lifetime = indexingRegistry.lifetime, ) } val jvmLibraryIndexingService = - indexingServiceManager.getService(JvmLibraryIndexingService.ID) as? JvmLibraryIndexingService? + manager.getService(JvmLibraryIndexingService.ID) as? JvmLibraryIndexingService? jvmLibraryIndexingService?.refresh() } @@ -249,6 +255,7 @@ class KotlinLanguageServer : ILanguageServer { override fun build( workspace: Workspace, layout: KotlinModuleLayout, + manager: IndexingServiceManager, ): Compiler { logger.info("Creating analysis session") @@ -256,7 +263,7 @@ class KotlinLanguageServer : ILanguageServer { JvmTarget.fromString(IJdkDistributionProvider.DEFAULT_JAVA_VERSION) ?: JvmTarget.JVM_21 - val model = KotlinProjectModel() + val model = KotlinProjectModel(manager.registry) model.update(workspace, JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget)) return Compiler( diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt index f4f2ded5f2..3e5c47b41c 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt @@ -1,6 +1,5 @@ package com.itsaky.androidide.lsp.kotlin.compiler -import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.api.Workspace import org.appdevforall.codeonthego.indexing.jvm.JVM_GENERATED_SYMBOL_INDEX import org.appdevforall.codeonthego.indexing.jvm.JVM_LIBRARY_SYMBOL_INDEX @@ -8,6 +7,7 @@ import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_META_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex +import org.appdevforall.codeonthego.indexing.service.IndexRegistry import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.slf4j.LoggerFactory @@ -23,7 +23,13 @@ import org.slf4j.LoggerFactory * (build complete), it notifies registered listeners so they can * refresh their sessions. */ -internal class KotlinProjectModel { +internal class KotlinProjectModel( + /* + * The registry of the project session this model was built for. Its indexes are looked up on each + * read because the generated index may register after the build. + */ + private val registry: IndexRegistry, +) { private val logger = LoggerFactory.getLogger(KotlinProjectModel::class.java) private var workspace: Workspace? = null @@ -32,36 +38,16 @@ internal class KotlinProjectModel { private val listeners = mutableListOf() val libraryIndex: JvmSymbolIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(JVM_LIBRARY_SYMBOL_INDEX) + get() = registry.get(JVM_LIBRARY_SYMBOL_INDEX) val sourceIndex: JvmSymbolIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(KT_SOURCE_FILE_INDEX_KEY) + get() = registry.get(KT_SOURCE_FILE_INDEX_KEY) val fileIndex: KtFileMetadataIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(KT_SOURCE_FILE_META_INDEX_KEY) + get() = registry.get(KT_SOURCE_FILE_META_INDEX_KEY) val generatedIndex: JvmSymbolIndex? - get() = - ProjectManagerImpl - .getInstance() - .indexingServiceManager - .registry - .get(JVM_GENERATED_SYMBOL_INDEX) + get() = registry.get(JVM_GENERATED_SYMBOL_INDEX) /** * The kind of change that occurred. diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt index b8d2beb95d..37614e70b7 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout +import org.appdevforall.codeonthego.indexing.service.IndexingServiceManager import org.junit.After import org.junit.Test import java.nio.file.Path @@ -177,6 +178,31 @@ class CompilerSessionTest { assertThat(session.current).isEqualTo("c1") } + @Test + fun `an update binds one manager for prepare and build`(): Unit = + runBlocking { + session.submit(workspace(LAYOUT_A)) + awaitEvent("ready c1") + + assertThat(lifecycle.obtainedManagers).hasSize(1) + assertThat(lifecycle.preparedWith.single()).isSameInstanceAs(lifecycle.builtWith.single()) + } + + @Test + fun `shutdown before binding obtains no manager`(): Unit = + runBlocking { + val gate = CompletableDeferred() + lifecycle.awaitClosedGate = gate + session.submit(workspace(LAYOUT_A)) + awaitEvent("awaitClosed") + + session.shutdown() + gate.complete(Unit) + delay(SETTLE_MILLIS) + + assertThat(lifecycle.obtainedManagers).isEmpty() + } + private fun workspace(layout: KotlinModuleLayout): Workspace = Workspace( rootProject = GradleProject(gradleProject(":")), @@ -211,7 +237,17 @@ class CompilerSessionTest { @Volatile var prepareGate: CompletableDeferred? = null - override fun prepare(workspace: Workspace) { + val obtainedManagers: MutableList = CopyOnWriteArrayList() + val preparedWith: MutableList = CopyOnWriteArrayList() + val builtWith: MutableList = CopyOnWriteArrayList() + + override fun currentManager() = IndexingServiceManager().also { obtainedManagers += it } + + override fun prepare( + workspace: Workspace, + manager: IndexingServiceManager, + ) { + preparedWith += manager events += "prepare" prepareGate?.let { runBlocking { it.await() } } } @@ -227,7 +263,9 @@ class CompilerSessionTest { override fun build( workspace: Workspace, layout: KotlinModuleLayout, + manager: IndexingServiceManager, ): String { + builtWith += manager val n = ++builds events += "building c$n" gates[n]?.let { runBlocking { it.await() } } diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt new file mode 100644 index 0000000000..55d4ac4600 --- /dev/null +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModelIndexTest.kt @@ -0,0 +1,26 @@ +package com.itsaky.androidide.lsp.kotlin.compiler + +import com.google.common.truth.Truth.assertThat +import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.jvm.JVM_LIBRARY_SYMBOL_INDEX +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.service.IndexRegistry +import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer +import org.junit.Test + +class KotlinProjectModelIndexTest { + @Test + fun `index getters read the bound registry, not the global manager`() { + val registry = IndexRegistry() + val backing = InMemoryIndex(JvmSymbolDescriptor) + val library = JvmSymbolIndex(backing, BackgroundIndexer(backing)) + registry.register(JVM_LIBRARY_SYMBOL_INDEX, library) + + val libraryIndex = runCatching { newModel(registry).libraryIndex } + + assertThat(libraryIndex.getOrNull()).isSameInstanceAs(library) + } + + private fun newModel(registry: IndexRegistry) = KotlinProjectModel(registry) +} From d3c877b2b8528e217207f8bc22174b04f3b78379 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:51:28 +0000 Subject: [PATCH 06/12] ADFA-6731: End a Kotlin build quietly when its project closes, and release the half-built environment --- .../androidide/lsp/kotlin/CompilerSession.kt | 9 ++- .../kotlin/compiler/CompilationEnvironment.kt | 25 ++++++-- .../lsp/kotlin/compiler/KotlinProjectModel.kt | 10 ++++ .../lsp/kotlin/CompilerSessionTest.kt | 58 +++++++++++++++++++ 4 files changed, 97 insertions(+), 5 deletions(-) diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt index 02f64da8f7..a4726ce8a7 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/CompilerSession.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch +import org.appdevforall.codeonthego.indexing.service.IndexRegistryClosedException import org.appdevforall.codeonthego.indexing.service.IndexingServiceManager import org.slf4j.LoggerFactory @@ -83,7 +84,11 @@ internal class CompilerSession( } catch (e: CancellationException) { throw e } catch (e: Throwable) { - logger.error("Kotlin project update failed", e) + if (e.isProjectClosed()) { + logger.info("Project closed during a Kotlin update; dropping it") + } else { + logger.error("Kotlin project update failed", e) + } } } } @@ -148,6 +153,8 @@ internal class CompilerSession( private fun isStopped() = synchronized(lock) { isShutDown } + private fun Throwable.isProjectClosed() = generateSequence(this) { it.cause }.any { it is IndexRegistryClosedException } + private fun awaitClosed(): Boolean { if (lifecycle.awaitClosed()) return true logger.error("Skipping Kotlin setup: the previous compiler is still closing") diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt index c7ae751009..5c9ea19594 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/CompilationEnvironment.kt @@ -28,7 +28,10 @@ import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import org.appdevforall.codeonthego.indexing.jvm.JVM_LIBRARY_SYMBOL_INDEX import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_INDEX_KEY +import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_META_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex import org.jetbrains.kotlin.analysis.api.KaImplementationDetail import org.jetbrains.kotlin.analysis.api.platform.analysisMessageBus @@ -111,19 +114,19 @@ internal class CompilationEnvironment( get() = ktProject.libraryIndex val requireLibraryIndex: JvmSymbolIndex - get() = checkNotNull(libraryIndex) + get() = ktProject.requireIndex(JVM_LIBRARY_SYMBOL_INDEX) val sourceIndex: JvmSymbolIndex? get() = ktProject.sourceIndex val requireSourceIndex: JvmSymbolIndex - get() = checkNotNull(sourceIndex) + get() = ktProject.requireIndex(KT_SOURCE_FILE_INDEX_KEY) val fileIndex: KtFileMetadataIndex? get() = ktProject.fileIndex val requireFileIndex: KtFileMetadataIndex - get() = checkNotNull(fileIndex) + get() = ktProject.requireIndex(KT_SOURCE_FILE_META_INDEX_KEY) val generatedIndex: JvmSymbolIndex? get() = ktProject.generatedIndex @@ -139,7 +142,21 @@ internal class CompilationEnvironment( } init { - initialize(::buildModules, ::buildKtSymbolIndex) + try { + initialize(::buildModules, ::buildKtSymbolIndex) + } catch (failure: Throwable) { + releaseAfterFailedInit(failure) + throw failure + } + } + + /* + * A throwing constructor never hands this instance to anyone who would close it, so the project + * environment initialize() already created would leak. super.close() rather than close(): the + * fields this class declares after its init block are still unset. + */ + private fun releaseAfterFailedInit(failure: Throwable) { + runCatching { super.close() }.exceptionOrNull()?.let(failure::addSuppressed) } @OptIn(KaImplementationDetail::class) diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt index 3e5c47b41c..c5718c4c36 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/KotlinProjectModel.kt @@ -7,7 +7,9 @@ import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KT_SOURCE_FILE_META_INDEX_KEY import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex +import org.appdevforall.codeonthego.indexing.service.IndexKey import org.appdevforall.codeonthego.indexing.service.IndexRegistry +import org.appdevforall.codeonthego.indexing.service.IndexRegistryClosedException import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.slf4j.LoggerFactory @@ -49,6 +51,14 @@ internal class KotlinProjectModel( val generatedIndex: JvmSymbolIndex? get() = registry.get(JVM_GENERATED_SYMBOL_INDEX) + /** + * Returns the index registered for [key]. + * + * @throws IndexRegistryClosedException if this model's project session has closed. + * @throws IllegalStateException if the session is open but nothing is registered for [key]. + */ + fun requireIndex(key: IndexKey): T = registry.require(key) + /** * The kind of change that occurred. */ diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt index 37614e70b7..ecd1874af0 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/CompilerSessionTest.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.lsp.kotlin import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.logging.provider.IdeLogRouter import com.itsaky.androidide.lsp.kotlin.compiler.KotlinModuleLayout import com.itsaky.androidide.lsp.kotlin.fixtures.gradleProject import com.itsaky.androidide.projects.api.GradleProject @@ -12,9 +13,12 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout +import org.appdevforall.codeonthego.indexing.service.IndexRegistryClosedException import org.appdevforall.codeonthego.indexing.service.IndexingServiceManager import org.junit.After +import org.junit.Before import org.junit.Test +import org.slf4j.event.Level import java.nio.file.Path import java.util.Collections import java.util.IdentityHashMap @@ -26,9 +30,17 @@ class CompilerSessionTest { private val scope = CoroutineScope(SupervisorJob()) private val lifecycle = FakeLifecycle() private val session = CompilerSession(scope, lifecycle) + private val logs: MutableList> = CopyOnWriteArrayList() + private val sink = IdeLogRouter.ExternalSink { level, _, message, _ -> logs += level to message } + + @Before + fun installSink() { + IdeLogRouter.addSink(sink) + } @After fun tearDown() { + IdeLogRouter.removeSink(sink) lifecycle.gates.values.forEach { it.complete(Unit) } lifecycle.awaitClosedGate?.complete(Unit) lifecycle.prepareGate?.complete(Unit) @@ -178,6 +190,42 @@ class CompilerSessionTest { assertThat(session.current).isEqualTo("c1") } + @Test + fun `a build that hits the closed registry logs no error`(): Unit = + runBlocking { + lifecycle.closedBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + delay(SETTLE_MILLIS) + + assertThat(updateFailures()).isEmpty() + assertThat(logs.filter { it.first == Level.INFO && "Project closed" in it.second }).hasSize(1) + } + + @Test + fun `a wrapped closed-registry failure logs no error`(): Unit = + runBlocking { + lifecycle.wrappedClosedBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + delay(SETTLE_MILLIS) + + assertThat(updateFailures()).isEmpty() + } + + @Test + fun `a failed build still logs an error`(): Unit = + runBlocking { + lifecycle.failingBuilds += 1 + session.submit(workspace(LAYOUT_A)) + awaitEvent("build failed c1") + delay(SETTLE_MILLIS) + + assertThat(updateFailures()).hasSize(1) + } + + private fun updateFailures() = logs.filter { it.first == Level.ERROR && "Kotlin project update failed" in it.second } + @Test fun `an update binds one manager for prepare and build`(): Unit = runBlocking { @@ -224,6 +272,8 @@ class CompilerSessionTest { val layouts: MutableMap = Collections.synchronizedMap(IdentityHashMap()) val gates = ConcurrentHashMap>() val failingBuilds: MutableSet = Collections.synchronizedSet(mutableSetOf()) + val closedBuilds: MutableSet = Collections.synchronizedSet(mutableSetOf()) + val wrappedClosedBuilds: MutableSet = Collections.synchronizedSet(mutableSetOf()) val awaitClosedResults = ConcurrentLinkedDeque() @Volatile @@ -273,6 +323,14 @@ class CompilerSessionTest { events += "build failed c$n" throw IllegalStateException("build $n failed") } + if (n in closedBuilds) { + events += "build failed c$n" + throw IndexRegistryClosedException("registry closed during build $n") + } + if (n in wrappedClosedBuilds) { + events += "build failed c$n" + throw RuntimeException("build $n failed", IndexRegistryClosedException("registry closed during build $n")) + } events += "build c$n for ${LAYOUT_NAMES.getValue(layout)}" return "c$n" } From a32401759def130c633c16e88271c6c037342206 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:57:21 +0000 Subject: [PATCH 07/12] ADFA-6731: Stop language servers before destroying the project, from one teardown --- .../editor/ProjectHandlerActivity.kt | 69 ++++++++++------ .../activities/editor/ProjectSessionCloser.kt | 60 ++++++++++++++ .../editor/ProjectSessionCloserTest.kt | 79 +++++++++++++++++++ .../androidide/lsp/api/ILanguageServer.kt | 6 +- 4 files changed, 186 insertions(+), 28 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt create mode 100644 app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 68050d4a53..baf7785a11 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -186,6 +186,12 @@ abstract class ProjectHandlerActivity : private val buildViewModel by viewModels() protected var initializingFuture: CompletableFuture? = null + + private val sessionCloser = + ProjectSessionCloser( + currentSession = { ProjectManagerImpl.getInstance().currentIndexingServiceManager }, + teardown = ::closeProjectSession, + ) private val Throwable?.isFileNotFound: Boolean get() = this is FileNotFoundException || @@ -1153,31 +1159,45 @@ abstract class ProjectHandlerActivity : override fun onPause() { super.onPause() - if (isDestroying) { - // reset these values here - // sometimes, when the IDE closed and reopened instantly, these values prevent initialization - // of the project - ProjectManagerImpl.getInstance().destroy() - - // ADFA-4128: the Quick Build session manager is a process-wide Koin - // singleton that outlives this activity, and its provisioner reads - // IProjectManager.getInstance().projectDirPath fresh at build time rather - // than a snapshot. Without this, closing a project while its eager prebuild - // (or a live session) is still in flight lets that work silently keep - // running once projectPath flips to whatever project opens next - either - // racing the next project's own prebuild() into a permanent no-op (the - // reducer treats a second PrebuildRequested while already Prebuilding as a - // no-op) or building against the wrong directory. restartSession() is a - // verified no-op when nothing is live (SessionReducerTest: "idle plus - // SessionRestartRequested is a no-op"). - quickBuildSessionManager()?.restartSession() + if (!isDestroying) return - editorViewModel.isInitializing = false - editorViewModel.isBuildInProgress = false - editorViewModel.isInternalBuildInProgress = false + if (didCompleteLiveOnCreate) { + sessionCloser.closeOnPause() + } else { + // A doomed instance must not stop the servers a live sibling uses; preDestroy gates them the same way. + closeProjectState() } } + private fun closeProjectSession() { + stopLanguageServers() + closeProjectState() + } + + private fun closeProjectState() { + // reset these values here + // sometimes, when the IDE closed and reopened instantly, these values prevent initialization + // of the project + ProjectManagerImpl.getInstance().destroy() + + // ADFA-4128: the Quick Build session manager is a process-wide Koin + // singleton that outlives this activity, and its provisioner reads + // IProjectManager.getInstance().projectDirPath fresh at build time rather + // than a snapshot. Without this, closing a project while its eager prebuild + // (or a live session) is still in flight lets that work silently keep + // running once projectPath flips to whatever project opens next - either + // racing the next project's own prebuild() into a permanent no-op (the + // reducer treats a second PrebuildRequested while already Prebuilding as a + // no-op) or building against the wrong directory. restartSession() is a + // verified no-op when nothing is live (SessionReducerTest: "idle plus + // SessionRestartRequested is a no-op"). + quickBuildSessionManager()?.restartSession() + + editorViewModel.isInitializing = false + editorViewModel.isBuildInProgress = false + editorViewModel.isInternalBuildInProgress = false + } + override fun onResume() { super.onResume() @@ -1232,11 +1252,7 @@ abstract class ProjectHandlerActivity : } if (didCompleteLiveOnCreate && isDestroying) { - try { - stopLanguageServers() - } catch (_: Exception) { - log.error("Failed to stop editor services.") - } + sessionCloser.closeOnDestroy() try { editorViewModel.unbindBuildService() @@ -1605,6 +1621,7 @@ abstract class ProjectHandlerActivity : protected open fun onProjectInitialized(result: InitializeResult.Success) { Memprof.mark("sync_complete") + sessionCloser.record(ProjectManagerImpl.getInstance().indexingServiceManager) editorActivityScope.launch(Dispatchers.IO) { val manager = ProjectManagerImpl.getInstance() val gradleBuildResult = diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt new file mode 100644 index 0000000000..3a2ca8b545 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt @@ -0,0 +1,60 @@ +package com.itsaky.androidide.activities.editor + +import org.slf4j.LoggerFactory + +/** + * Runs an editor's project-session teardown at most once, and only for the session it opened. + * + * The teardown stops the language servers before it destroys the project: a stopped server can no + * longer pick up the next project's indexing manager, and the indexes it still holds close quietly. + * It runs from `onPause` while finishing, because `isFinishing` is reliable there and the next + * editor may open a project before this one's `onDestroy`. A configuration change never runs it: + * `isFinishing` is false then, and the servers must survive the recreation. `preDestroy` calls it + * too, for a `finish()` that arrives while already paused. + * + * Servers, the project manager and Quick Build are process-wide, so the teardown is skipped when the + * current session is not the one [record]ed, which means another editor already owns them. The + * check only tells sessions apart when a new manager was created between them. + * + * @param currentSession Returns the current session without creating one. + * @param teardown Stops the servers and destroys the project. + */ +internal class ProjectSessionCloser( + private val currentSession: () -> S?, + private val teardown: () -> Unit, +) { + private companion object { + private val log = LoggerFactory.getLogger(ProjectSessionCloser::class.java) + } + + private var recorded: S? = null + private var tornDown = false + + /** Records [session] as the one this editor opened; ignored once the teardown has run. */ + fun record(session: S) { + if (tornDown) return + recorded = session + } + + /** Tears down when nothing was recorded (as before recording existed) or this editor still owns the session. */ + fun closeOnPause() { + if (recorded == null || ownsCurrent()) runTeardown() else skip("pause") + } + + /** Tears down only when this editor recorded a session and still owns it. */ + fun closeOnDestroy() { + if (recorded != null && ownsCurrent()) runTeardown() else skip("destroy") + } + + private fun ownsCurrent() = currentSession() === recorded + + private fun runTeardown() { + if (tornDown) return + tornDown = true + teardown() + } + + private fun skip(caller: String) { + if (!tornDown) log.info("Skipping project teardown on {}: this editor does not own the current session", caller) + } +} diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt new file mode 100644 index 0000000000..6b37ad2f2a --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt @@ -0,0 +1,79 @@ +package com.itsaky.androidide.activities.editor + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class ProjectSessionCloserTest { + private val first = Any() + private val second = Any() + private var current: Any? = null + private var teardowns = 0 + private val closer = ProjectSessionCloser({ current }, { teardowns++ }) + + @Test + fun `teardown runs once across repeated calls`() { + recordCurrent(first) + + closer.closeOnPause() + closer.closeOnPause() + closer.closeOnDestroy() + + assertThat(teardowns).isEqualTo(1) + } + + @Test + fun `pause with nothing recorded tears down as today`() { + closer.closeOnPause() + + assertThat(teardowns).isEqualTo(1) + } + + @Test + fun `destroy with nothing recorded skips`() { + closer.closeOnDestroy() + + assertThat(teardowns).isEqualTo(0) + } + + @Test + fun `skips when the current manager is not the recorded one`() { + recordCurrent(first) + current = second + + closer.closeOnPause() + closer.closeOnDestroy() + + assertThat(teardowns).isEqualTo(0) + } + + @Test + fun `destroy fallback runs when pause never closed`() { + recordCurrent(first) + + closer.closeOnDestroy() + + assertThat(teardowns).isEqualTo(1) + } + + @Test + fun `a closer that never ran its teardown does nothing on recreation`() { + recordCurrent(first) + + assertThat(teardowns).isEqualTo(0) + } + + @Test + fun `record after teardown is ignored`() { + closer.closeOnPause() + recordCurrent(second) + + closer.closeOnDestroy() + + assertThat(teardowns).isEqualTo(1) + } + + private fun recordCurrent(session: Any) { + current = session + closer.record(session) + } +} diff --git a/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt b/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt index 2e0cd7e558..447e6399c7 100644 --- a/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt +++ b/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt @@ -76,8 +76,10 @@ interface ILanguageServer { * Called by client to notify the server to shutdown. Language servers must release all the * resources in use. * - * - * After this is called, clients must re-initialize the server. + * Called once when the project closes, from the editor's `onPause` while it finishes, and never + * on an activity recreation. It must not block. The project's indexes may close at any time after + * it returns; reads of a closed index return empty results. After this is called, clients must + * re-initialize the server. */ fun shutdown() From 0c9e56cfe7d4115ba32f27472c8247d061cfd3ac Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 04:58:03 +0000 Subject: [PATCH 08/12] ADFA-6731: Document the project session teardown order --- ARCHITECTURE.md | 2 ++ .../com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9265376845..00b6a90fe5 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -63,6 +63,8 @@ The optional file path is attacker-controllable (a URL segment), so it's resolve Whether the open project *can* be named at all is `isDeepLinkTargetOfOpenProject` (`ProjectValidations.kt`): a link can only ever resolve to `/`, but a project can be opened from anywhere. Its `deepLinkTargetOfOpenProjectWithoutIo` half exists so a caller on the main thread can settle the common case — equal path strings name the same directory — without the `canonicalPath` calls the full rule needs. `CreateLinkAction` sends its residue to `Dispatchers.IO` rather than to the StrictMode whitelist (ADR 0007); the two older callers (`EditorHandlerActivity.onNewIntent`, `BaseEditorActivity.onCreate`) still fall through to `canonicalPath` on the main thread and have not been migrated, so the shortcut narrows that exposure rather than removing it. +**Project session lifecycle: language servers stop before the project is destroyed, and only when the editor finishes.** Closing a project runs one teardown from `ProjectHandlerActivity.onPause` while the activity finishes (`ProjectSessionCloser`, with a `preDestroy` fallback for a `finish()` that arrives while already paused). Its order is the contract: (1) every language server's `shutdown()`, which must not block; (2) `ProjectManagerImpl.destroy()`, which ends the `IndexingServiceManager`'s session lifetime at once and closes its services and `IndexRegistry` in the background; (3) the Quick Build session restart. The next project's manager waits for that background close before it reopens the index databases, which are global files. Work the old session still has in flight may touch its closed indexes: reads return empty results, and `SQLiteIndex` logs that at DEBUG because the lifetime has ended (use after close in a live session stays ERROR, since it is a real bug). A closed registry refuses new indexes with `IndexRegistryClosedException`, which the Kotlin server's `CompilerSession` treats as the end of an update, not a failure. Each Kotlin project update binds one manager, under the same lock as its shutdown check, so a closing session never reads or writes the next session's indexes. A configuration change (rotation, font scale, dark mode) never runs the teardown: `isFinishing` is false, and servers and indexes survive the recreation. Other readers of the global `ProjectManagerImpl.indexingServiceManager` (the project setup, `GradleBuildService`, the Java and XML class lookups) are not bound to a session yet; a manager that sees a sync before any service registers retries setup on the next sync instead of staying empty. + ## Module Structure Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle build has ~80 modules (`settings.gradle.kts`) plus three included composite builds. `app` is the integration point; the rest are libraries it composes. diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt index 4e9e062c0b..98b6f32dc7 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinLanguageServer.kt @@ -133,8 +133,8 @@ class KotlinLanguageServer : ILanguageServer { private val logger = LoggerFactory.getLogger(KotlinLanguageServer::class.java) /** - * Runs every Compiler.close(), which blocks draining workers and is reached from - * ProjectHandlerActivity.onDestroy on the main thread. One thread serializes closes; the next + * Runs every Compiler.close(), which blocks draining workers and is reached from the editor's + * project teardown in ProjectHandlerActivity.onPause, on the main thread. One thread serializes closes; the next * build waits so a new compiler never starts while the previous one is still disposing. */ private val closeExecutor = From 8182007700635a752a04e35337d0df46d28d465a Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 05:20:09 +0000 Subject: [PATCH 09/12] ADFA-6731: Refuse new indexes as soon as the session ends, not when the background close reaches the registry --- .../indexing/service/IndexRegistry.kt | 19 +++++++++------ .../indexing/service/IndexRegistryTest.kt | 24 +++++++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt index 5d09a3d7be..1d22dac8d6 100644 --- a/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt +++ b/lsp/indexing/src/main/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistry.kt @@ -31,9 +31,14 @@ class IndexRegistry( @Volatile private var closed = false - /** Whether [close] has been called. */ + /** + * Whether [close] has been called or this registry's session has ended. + * + * The lifetime ends as soon as the manager closes, while [close] runs later in the background, so + * an ended lifetime already counts as closed. + */ val isClosed: Boolean - get() = closed + get() = closed || lifetime.isEnded /** * Register an index. Replaces any previously registered index @@ -48,13 +53,13 @@ class IndexRegistry( key: IndexKey, index: T, ) { - if (closed) { + if (isClosed) { (index as? Closeable)?.close() throw closedException(key) } val old = indexes.put(key.name, index) - if (closed) { + if (isClosed) { // close() may have drained the map before this entry landed; whoever removes it closes it. if (indexes.remove(key.name, index)) (index as? Closeable)?.close() throw closedException(key) @@ -92,11 +97,11 @@ class IndexRegistry( key: IndexKey, create: () -> T, ): T { - if (closed) throw closedException(key) + if (isClosed) throw closedException(key) var created: T? = null val index = indexes.computeIfAbsent(key.name) { create().also { created = it } } - if (closed) { + if (isClosed) { // close() may have drained the map before this entry landed; whoever removes it closes it. if (indexes.remove(key.name, index)) (index as? Closeable)?.close() throw closedException(key) @@ -121,7 +126,7 @@ class IndexRegistry( * @throws IllegalStateException if the registry is open but nothing is registered for [key]. */ fun require(key: IndexKey): T = - get(key) ?: if (closed) { + get(key) ?: if (isClosed) { throw closedException(key) } else { throw IllegalStateException( diff --git a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt index b933f4513c..cca82a55e7 100644 --- a/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt +++ b/lsp/indexing/src/test/kotlin/org/appdevforall/codeonthego/indexing/service/IndexRegistryTest.kt @@ -217,6 +217,30 @@ class IndexRegistryTest { assertThat(registry.get(keyA)).isNull() } + @Test + fun `registerIfAbsent after the session ended does not create and throws`() { + val registry = IndexRegistry() + registry.lifetime.end() + var created = false + + assertThrows(IndexRegistryClosedException::class.java) { + registry.registerIfAbsent(keyA) { + created = true + "created" + } + } + + assertThat(created).isFalse() + } + + @Test + fun `require of a missing index after the session ended throws the closed exception`() { + val registry = IndexRegistry() + registry.lifetime.end() + + assertThrows(IndexRegistryClosedException::class.java) { registry.require(keyA) } + } + @Test fun `register after close closes the given index and throws`() { val registry = IndexRegistry() From 561360c6f6b0f50f7ef6dbb88c12516feb8e2ad4 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 05:20:09 +0000 Subject: [PATCH 10/12] ADFA-6731: Tear down from preDestroy when the editor never recorded its session --- .../editor/ProjectHandlerActivity.kt | 6 ++-- .../activities/editor/ProjectSessionCloser.kt | 23 ++++++--------- .../editor/ProjectSessionCloserTest.kt | 29 +++++++------------ .../androidide/lsp/api/ILanguageServer.kt | 4 +-- 4 files changed, 25 insertions(+), 37 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index baf7785a11..ec760d8b0c 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1162,7 +1162,7 @@ abstract class ProjectHandlerActivity : if (!isDestroying) return if (didCompleteLiveOnCreate) { - sessionCloser.closeOnPause() + sessionCloser.close() } else { // A doomed instance must not stop the servers a live sibling uses; preDestroy gates them the same way. closeProjectState() @@ -1180,7 +1180,7 @@ abstract class ProjectHandlerActivity : // of the project ProjectManagerImpl.getInstance().destroy() - // ADFA-4128: the Quick Build session manager is a process-wide Koin + // The Quick Build session manager is a process-wide Koin // singleton that outlives this activity, and its provisioner reads // IProjectManager.getInstance().projectDirPath fresh at build time rather // than a snapshot. Without this, closing a project while its eager prebuild @@ -1252,7 +1252,7 @@ abstract class ProjectHandlerActivity : } if (didCompleteLiveOnCreate && isDestroying) { - sessionCloser.closeOnDestroy() + sessionCloser.close() try { editorViewModel.unbindBuildService() diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt index 3a2ca8b545..69caa8c9e1 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt @@ -13,8 +13,10 @@ import org.slf4j.LoggerFactory * too, for a `finish()` that arrives while already paused. * * Servers, the project manager and Quick Build are process-wide, so the teardown is skipped when the - * current session is not the one [record]ed, which means another editor already owns them. The - * check only tells sessions apart when a new manager was created between them. + * current session is not the one [record]ed, which means another editor already owns them. With + * nothing recorded (the project never finished opening, or a recreated editor skipped it) it tears + * down as before recording existed. The check only tells sessions apart when a new manager was + * created between them. * * @param currentSession Returns the current session without creating one. * @param teardown Stops the servers and destroys the project. @@ -36,25 +38,18 @@ internal class ProjectSessionCloser( recorded = session } - /** Tears down when nothing was recorded (as before recording existed) or this editor still owns the session. */ - fun closeOnPause() { - if (recorded == null || ownsCurrent()) runTeardown() else skip("pause") + /** Tears down when nothing was recorded or this editor still owns the current session. */ + fun close() { + if (recorded == null || currentSession() === recorded) runTeardown() else skip() } - /** Tears down only when this editor recorded a session and still owns it. */ - fun closeOnDestroy() { - if (recorded != null && ownsCurrent()) runTeardown() else skip("destroy") - } - - private fun ownsCurrent() = currentSession() === recorded - private fun runTeardown() { if (tornDown) return tornDown = true teardown() } - private fun skip(caller: String) { - if (!tornDown) log.info("Skipping project teardown on {}: this editor does not own the current session", caller) + private fun skip() { + if (!tornDown) log.info("Skipping project teardown: this editor does not own the current session") } } diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt index 6b37ad2f2a..feff51afaa 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt @@ -14,43 +14,36 @@ class ProjectSessionCloserTest { fun `teardown runs once across repeated calls`() { recordCurrent(first) - closer.closeOnPause() - closer.closeOnPause() - closer.closeOnDestroy() + closer.close() + closer.close() + closer.close() assertThat(teardowns).isEqualTo(1) } @Test - fun `pause with nothing recorded tears down as today`() { - closer.closeOnPause() + fun `nothing recorded tears down as before`() { + closer.close() assertThat(teardowns).isEqualTo(1) } - @Test - fun `destroy with nothing recorded skips`() { - closer.closeOnDestroy() - - assertThat(teardowns).isEqualTo(0) - } - @Test fun `skips when the current manager is not the recorded one`() { recordCurrent(first) current = second - closer.closeOnPause() - closer.closeOnDestroy() + closer.close() + closer.close() assertThat(teardowns).isEqualTo(0) } @Test - fun `destroy fallback runs when pause never closed`() { + fun `an editor that still owns its session tears it down`() { recordCurrent(first) - closer.closeOnDestroy() + closer.close() assertThat(teardowns).isEqualTo(1) } @@ -64,10 +57,10 @@ class ProjectSessionCloserTest { @Test fun `record after teardown is ignored`() { - closer.closeOnPause() + closer.close() recordCurrent(second) - closer.closeOnDestroy() + closer.close() assertThat(teardowns).isEqualTo(1) } diff --git a/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt b/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt index 447e6399c7..6c67e9d9bd 100644 --- a/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt +++ b/lsp/api/src/main/java/com/itsaky/androidide/lsp/api/ILanguageServer.kt @@ -76,8 +76,8 @@ interface ILanguageServer { * Called by client to notify the server to shutdown. Language servers must release all the * resources in use. * - * Called once when the project closes, from the editor's `onPause` while it finishes, and never - * on an activity recreation. It must not block. The project's indexes may close at any time after + * Called once when the project closes (normally from the editor's `onPause` while it finishes) or + * when the server is unregistered, and never on an activity recreation. It must not block. The project's indexes may close at any time after * it returns; reads of a closed index return empty results. After this is called, clients must * re-initialize the server. */ From 6aac11701bad9db75ff724cb2dbb568c60c5eeb0 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 27 Oct 2026 07:09:00 +0000 Subject: [PATCH 11/12] ADFA-6731: Cancel the Kotlin index worker on close instead of draining its queue --- .../kotlin/compiler/index/KtSymbolIndex.kt | 8 ++- .../compiler/index/KtSymbolIndexCloseTest.kt | 68 +++++++++++++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt index b471b860e6..92d2ac79f9 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndex.kt @@ -583,10 +583,12 @@ internal class KtSymbolIndex( } suspend fun close() { - indexWorker.submitCommand(IndexCommand.Stop) - + /* + * Cancel the worker rather than queueing a stop: a stop waits behind every queued file, and + * a large pass outlasts the caller's bounded wait, so disposal would proceed under a live worker. + */ scanningJob?.cancelAndJoin() - indexingJob?.join() + indexingJob?.cancelAndJoin() /* * Cancel AND JOIN the index's own scope. Beyond the main worker loop drained above, the diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt new file mode 100644 index 0000000000..8a3e46ecd9 --- /dev/null +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/compiler/index/KtSymbolIndexCloseTest.kt @@ -0,0 +1,68 @@ +package com.itsaky.androidide.lsp.kotlin.compiler.index + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.lsp.kotlin.fixtures.KtLspTest +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.appdevforall.codeonthego.indexing.InMemoryIndex +import org.appdevforall.codeonthego.indexing.api.Index +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolDescriptor +import org.appdevforall.codeonthego.indexing.jvm.JvmSymbolIndex +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadata +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataDescriptor +import org.appdevforall.codeonthego.indexing.jvm.KtFileMetadataIndex +import org.appdevforall.codeonthego.indexing.util.BackgroundIndexer +import org.junit.Test +import java.nio.file.Paths +import java.util.concurrent.atomic.AtomicInteger + +class KtSymbolIndexCloseTest : KtLspTest() { + private val fileIndexReads = AtomicInteger() + + private fun slowFileIndex(): KtFileMetadataIndex { + val backing = InMemoryIndex(KtFileMetadataDescriptor) + return KtFileMetadataIndex( + object : Index by backing { + override suspend fun get(key: String): KtFileMetadata? { + fileIndexReads.incrementAndGet() + delay(READ_DELAY_MILLIS) + return backing.get(key) + } + }, + ) + } + + private fun jvmIndex(): JvmSymbolIndex { + val backing = InMemoryIndex(JvmSymbolDescriptor) + return object : JvmSymbolIndex(backing, BackgroundIndexer(backing)) { + override fun visibleSourceIds(): Collection? = null + } + } + + @Test + fun `close stops the worker without draining queued index work`(): Unit = + runBlocking { + val path = Paths.get(createSourceFile("Sample.kt", "fun foo() = 1").virtualFile.path) + val symbols = jvmIndex() + val index = + KtSymbolIndex( + kind = env.ktSymbolIndex.kind, + project = env.project, + modules = emptyList(), + fileIndex = slowFileIndex(), + sourceIndex = symbols, + libraryIndex = symbols, + ) + index.refreshSources() + repeat(QUEUED_FILES) { index.submitForIndexing(path) } + + index.close() + + assertThat(fileIndexReads.get()).isLessThan(QUEUED_FILES) + } + + private companion object { + const val QUEUED_FILES = 30 + const val READ_DELAY_MILLIS = 20L + } +} From f0640b6f5446d162965f819bd08c300047076bf7 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Thu, 29 Oct 2026 12:54:15 +0000 Subject: [PATCH 12/12] ADFA-6731: Cancel project initialization on close and refuse a session recorded after the teardown --- .../editor/ProjectHandlerActivity.kt | 9 ++++++- .../activities/editor/ProjectSessionCloser.kt | 19 ++++++++++--- .../editor/ProjectSessionCloserTest.kt | 27 ++++++++++++++++++- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index c4ada567d2..a53867080b 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1180,6 +1180,9 @@ abstract class ProjectHandlerActivity : if (!isDestroying) return if (didCompleteLiveOnCreate) { + // The teardown below destroys the project, so a sync finishing after it must not set one up again. + initializingFuture?.cancel(true) + initializingFuture = null sessionCloser.close() } else { // A doomed instance must not stop the servers a live sibling uses; preDestroy gates them the same way. @@ -1781,8 +1784,12 @@ abstract class ProjectHandlerActivity : result: InitializeResult.Success, synced: Boolean, ) { + // A callback queued before onPause cancelled the future still lands here after the teardown. + if (!sessionCloser.record { ProjectManagerImpl.getInstance().indexingServiceManager }) { + log.info("Project closed before its initialization finished, skipping its setup") + return + } Memprof.mark("sync_complete") - sessionCloser.record(ProjectManagerImpl.getInstance().indexingServiceManager) editorActivityScope.launch(Dispatchers.IO) { val manager = ProjectManagerImpl.getInstance() val gradleBuildResult = diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt index 69caa8c9e1..665247879c 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectSessionCloser.kt @@ -18,6 +18,9 @@ import org.slf4j.LoggerFactory * down as before recording existed. The check only tells sessions apart when a new manager was * created between them. * + * [record] runs on the project initialization callback's thread and [close] on the main thread, so + * both hold the lock: a session recorded after the teardown would never be closed. + * * @param currentSession Returns the current session without creating one. * @param teardown Stops the servers and destroys the project. */ @@ -32,13 +35,21 @@ internal class ProjectSessionCloser( private var recorded: S? = null private var tornDown = false - /** Records [session] as the one this editor opened; ignored once the teardown has run. */ - fun record(session: S) { - if (tornDown) return - recorded = session + /** + * Records the session [session] returns as the one this editor opened, and returns whether it did. + * + * Once the teardown has run it returns false without calling [session], since resolving a session + * may create one that nothing would close. + */ + @Synchronized + fun record(session: () -> S): Boolean { + if (tornDown) return false + recorded = session() + return true } /** Tears down when nothing was recorded or this editor still owns the current session. */ + @Synchronized fun close() { if (recorded == null || currentSession() === recorded) runTeardown() else skip() } diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt index feff51afaa..66abc6ffc2 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/ProjectSessionCloserTest.kt @@ -65,8 +65,33 @@ class ProjectSessionCloserTest { assertThat(teardowns).isEqualTo(1) } + @Test + fun `record after teardown reports that it was refused`() { + closer.close() + + assertThat(closer.record { second }).isFalse() + } + + @Test + fun `record after teardown never resolves the session`() { + var resolved = false + closer.close() + + closer.record { + resolved = true + second + } + + assertThat(resolved).isFalse() + } + + @Test + fun `record before teardown is accepted`() { + assertThat(closer.record { first }).isTrue() + } + private fun recordCurrent(session: Any) { current = session - closer.record(session) + closer.record { session } } }