Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
a3d2188
ADFA-6731: Refuse and close indexes registered after the registry closes
itsaky-adfa Oct 27, 2026
6744c7a
ADFA-6731: Log use of a closed index at DEBUG once its session has ended
itsaky-adfa Oct 27, 2026
940a314
ADFA-6731: Stop indexing setup quietly when the session closes, and r…
itsaky-adfa Oct 27, 2026
d536190
ADFA-6731: Record the indexing close before a new manager can be created
itsaky-adfa Oct 27, 2026
cd29e80
ADFA-6731: Bind each Kotlin project update to one indexing manager
itsaky-adfa Oct 27, 2026
d3c877b
ADFA-6731: End a Kotlin build quietly when its project closes, and re…
itsaky-adfa Oct 27, 2026
a324017
ADFA-6731: Stop language servers before destroying the project, from …
itsaky-adfa Oct 27, 2026
0c9e56c
ADFA-6731: Document the project session teardown order
itsaky-adfa Oct 27, 2026
8182007
ADFA-6731: Refuse new indexes as soon as the session ends, not when t…
itsaky-adfa Oct 27, 2026
561360c
ADFA-6731: Tear down from preDestroy when the editor never recorded i…
itsaky-adfa Oct 27, 2026
6aac117
ADFA-6731: Cancel the Kotlin index worker on close instead of drainin…
itsaky-adfa Oct 27, 2026
70cfa88
Merge branch 'stage' into fix/ADFA-6731
itsaky-adfa Oct 27, 2026
4ad9a2f
Merge branch 'stage' into fix/ADFA-6731
itsaky-adfa Oct 28, 2026
7dc99c6
Merge branch 'stage' into fix/ADFA-6731
itsaky-adfa Oct 29, 2026
f0640b6
ADFA-6731: Cancel project initialization on close and refuse a sessio…
itsaky-adfa Oct 29, 2026
1161c22
Merge remote-tracking branch 'origin/fix/ADFA-6731' into fix/ADFA-6731
itsaky-adfa Oct 29, 2026
f54fff7
Merge branch 'stage' into fix/ADFA-6731
itsaky-adfa Oct 29, 2026
db1bed9
Merge branch 'stage' into fix/ADFA-6731
itsaky-adfa Oct 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,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 `<projectsRoot>/<name>`, 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.

**Gradle build output lives in app storage, not the project folder (ADFA-4930).** Projects sit on shared storage (`/sdcard`), which Android serves through FUSE, so every file a build writes pays a user-space round trip. Each project's build output goes to `noBackupFilesDir/gradle-build/<projectKey>/` (`services/builder/BuildOutputLocation`), keyed like Quick Build's scratch (`ProjectStorageKey` in `:shared`):
- `main/<name>-<hash>/` per Gradle project (`<hash>` of its full path, so `:core:ui` is not inside `:core`'s output); nested builds get their own key. The init script plugin sets `layout.buildDirectory` from `-Pcotg.build.outputDir` (`gradle-plugin/.../BuildOutputRedirect`).
- `project-cache/` (`--project-cache-dir`, Gradle's `.gradle/`) and `kotlin/` (`kotlin.project.persistent.dir`), for the main build; an included build keeps its own, as Gradle passes neither setting to it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ abstract class ProjectHandlerActivity :

private val buildViewModel by viewModels<BuildViewModel>()
protected var initializingFuture: CompletableFuture<out InitializeResult?>? = null

private val sessionCloser =
ProjectSessionCloser(
currentSession = { ProjectManagerImpl.getInstance().currentIndexingServiceManager },
teardown = ::closeProjectSession,
)
private val Throwable?.isFileNotFound: Boolean
get() =
this is FileNotFoundException ||
Expand Down Expand Up @@ -1171,31 +1177,48 @@ 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) {
// 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.
closeProjectState()
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved
}
}

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()
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved

// 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()

Expand Down Expand Up @@ -1372,11 +1395,7 @@ abstract class ProjectHandlerActivity :
}

if (didCompleteLiveOnCreate && isDestroying) {
try {
stopLanguageServers()
} catch (_: Exception) {
log.error("Failed to stop editor services.")
}
sessionCloser.close()

try {
editorViewModel.unbindBuildService()
Expand Down Expand Up @@ -1765,6 +1784,11 @@ 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")
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved
editorActivityScope.launch(Dispatchers.IO) {
val manager = ProjectManagerImpl.getInstance()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
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. 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.
*
* [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.
*/
internal class ProjectSessionCloser<S : Any>(
private val currentSession: () -> S?,
private val teardown: () -> Unit,
) {
private companion object {
private val log = LoggerFactory.getLogger(ProjectSessionCloser::class.java)
}

private var recorded: S? = null
Comment thread
itsaky-adfa marked this conversation as resolved.
Resolved
private var tornDown = false

/**
* 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()
}

private fun runTeardown() {
if (tornDown) return
tornDown = true
teardown()
}

private fun skip() {
if (!tornDown) log.info("Skipping project teardown: this editor does not own the current session")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
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.close()
closer.close()
closer.close()

assertThat(teardowns).isEqualTo(1)
}

@Test
fun `nothing recorded tears down as before`() {
closer.close()

assertThat(teardowns).isEqualTo(1)
}

@Test
fun `skips when the current manager is not the recorded one`() {
recordCurrent(first)
current = second

closer.close()
closer.close()

assertThat(teardowns).isEqualTo(0)
}

@Test
fun `an editor that still owns its session tears it down`() {
recordCurrent(first)

closer.close()

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.close()
recordCurrent(second)

closer.close()

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 }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 (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.
*/
fun shutdown()

Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<T : Indexable>(
override val descriptor: IndexDescriptor<T>,
Expand All @@ -110,6 +112,7 @@ class SQLiteIndex<T : Indexable>(
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<T>,
PackageTree {
companion object {
Expand Down Expand Up @@ -560,12 +563,17 @@ class SQLiteIndex<T : Indexable>(

/*
* 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,
Expand Down
Loading
Loading